You get a bonus - 1 coin for daily activity. Now you have 1 coin

bash/sh: Replacing Characters or Substrings in a String in Shell Scripts

Practice



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

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "LINUX operating system"

Terms: LINUX operating system