1

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 unix.stackexchange.com/questions/112023/… 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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.