I want to change all of the words in a text who matches a certain word with another one in bourne shell. For example:
hello sara, my name is sara too.
becomes:
hello mary, my name is mary too.
Can anybody help me?
I know that grep find similar words but I want to replace them with other word.
To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.
The Bash logical (&&) operator is one of the most useful commands that can be used in multiple ways, like you can use in the conditional statement or execute multiple commands simultaneously.
Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .
Pure bash way:
before='hello sara , my name is sara too .'
after="${before//sara/mary}"
echo "$after"
OR using sed:
after=$(sed 's/sara/mary/g' <<< "$before")
echo "$after"
OUTPUT:
hello mary , my name is mary too .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With