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.

  • 1
    something like sed -i.orig 's/abc/xyz/' <list of files> see https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files for detailed discussion on replacing strings – Sundeep Jul 13 '16 at 13:57
  • and <list of files> can be something like $(grep -l abc *.txt) to get list of files ending with .txt containing the string abc – Sundeep Jul 13 '16 at 14:04
  • I meant all files in a folder. Changing the description... – AlikElzin-kilaka Jul 13 '16 at 15:22
  • does any of these answers helped you ? – Rahul Jul 14 '16 at 12:27

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,589