2

I'd like to recursively search for a string within all files in a folder.

If the string was found, backup the file to the same location (copy to <filename>-orig) and replace the found string with another string.

How to do it?

Can I do it with a single command? Thanks.

AlikElzin-kilaka
  • 561
  • 1
  • 8
  • 20

1 Answers1

1

You can combine two -exec operation of find, firstly to find all files containing matching string and secondly to replace the string with replace keyword (keeping backup of original file), like

find . -type f -exec grep -il "searchstring" {} \; -exec sed -i.bak \
's/searchstring/replacestring/' {} \;

Explanation :

  • -exec grep -il "searchstring" : search for "searchsring"
  • -exec sed -i.bak 's/searchstring/replacestring/' : If any files found containing string then keep backup of file their and replace with "replacestring".

Note that in this case the second command will only run if the first one returns successfully.

Rahul
  • 13,309
  • 3
  • 43
  • 54