Substitute a text only in files where it appears

Wednesday, December 3, 2014 · 1 minute · 82 words

For example, to substitute foo with bar

for f in `grep -lR foo`; do
  echo -n ">> $f";
  sed 's/foo/bar/g' $f > $f.2;
  mv $f.2 $f;
  echo " done.";
  • for loops on all files containing the text “foo”, grep -l only show the file name with corresponding text inside.
  • sed replace foo with bar in all file
  • mv save the modification (delete if you don’t want to overwrite the original files, the modified files is named with .2 at the end)
linux shell