Search and Replace in Linux

Suppose you want to replace some text in a file using Bash. You can easily do this with the sed command

sed -i "s/SEARCH TEXT/REPLACE TEXT/g" filename(s)

for example, replace your name from “your name” to “new name”

sed -i "s/your name/new name/g" file1.txt file2.txt

In a bash script you could do something similar to

   for files in find /path/to/my/files -type f
do sed -i "s/your name/new name/g" $files done

Some notes

  • The “-i” is “ignore case”. Leave this out to be case specific.
  • The “g” at the end means “replace all occurrences”. If you leave this off, only the first occurrences will be replaced. Or you can place a number instead to say how many occurrences to replace.

sed is a stream editor application. More information about sed can be found here –