Reputation: 375
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.
Upvotes: 17
Views: 50585
Reputation: 785008
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 .
Upvotes: 20
Reputation: 77085
Or awk
awk '{gsub("sara","mary")}1' <<< "hello sara, my name is sara too."
Upvotes: 1
Reputation: 22252
You can use sed:
# sed 's/sara/mary/g' FILENAME
will output the results. The s/// construct means search and replace using regular expressions. The 'g' at the end means "every instance" (not just the first).
You can also use perl and edit the file in place:
# perl -p -i -e 's/sara/mary/g;' FILENAME
Upvotes: 4
Reputation: 95298
You can use sed for that:
$ sed s/sara/mary/g <<< 'hello sara , my name is sara too .'
hello mary , my name is mary too .
Or if you want to change a file in place:
$ cat FILE
hello sara , my name is sara too .
$ sed -i s/sara/mary/g FILE
$ cat FILE
hello mary , my name is mary too .
Upvotes: 12