Replace a word with another in bash

41,592

Solution 1

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 .

Solution 2

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 .

Solution 3

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

Solution 4

Or awk

awk '{gsub("sara","mary")}1' <<< "hello sara, my name is sara too."
Share:
41,592
reza
Author by

reza

Updated on January 20, 2020

Comments

  • reza
    reza over 4 years

    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.

  • Niklas B.
    Niklas B. over 12 years
    sed can also do in-place-modification.
  • galath
    galath over 8 years
    The input string would better be named something other than s, to avoid confusion in ${s//sara/mary} and 's/sara/mary/g'.
  • user140259
    user140259 over 5 years
    Thanks, this solved my problem, but how could you print $after in the sed syntax if it is not defined?
  • anubhava
    anubhava over 5 years
    Use after=$(sed 's/sara/mary/g' <<< "$before")