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, 2016 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, 2016 at 14:04
  • I meant all files in a folder. Changing the description... Jul 13, 2016 at 15:22
  • does any of these answers helped you ?
    – Rahul
    Jul 14, 2016 at 12:27

1 Answer 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .