Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a word with another in bash

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.

like image 976
reza Avatar asked Feb 04 '12 15:02

reza


People also ask

How do I replace a character in a string in bash?

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.

What is && in bash?

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.

How do you replace a word in VI Linux?

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 .


1 Answers

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 .
like image 182
anubhava Avatar answered Sep 17 '22 17:09

anubhava