Task: replace one set of characters in a string with another set (as a special case — replace all occurrences of a single character with another, for example, replace all "A" with "B", or all spaces with underscores, and so on).
Really, nothing complicated about it. Here's a piece of code where, as an example, we replace all "D" characters with "T" characters:
echo "DHIS IS DEST" | sed 's/D/T/g'
And here's the same example, but in a script file:
#!/bin/sh
myvar=`echo "DHIS IS DEST" | sed 's/D/T/g'`
echo "${myvar}"
So, the syntax:
echo "source_string" | sed 's/what_to_replace/what_to_replace_with/g'
where
- source_string: this is the string within which the characters need to be changed
- what_to_replace: this is the character or substring to search for in the source string
- what_to_replace_with: this is the character or substring to replace all found fragments WITH
Comments