Test recursive sed search and replace before running

sed

Is there any way to run a trial recursive search and replace using sed, before actually running it? I just want to print out the results before actually doing the search and replace. Something like echoing the results of,

grep -rl term1 . |xargs sed -i -e 's/term1/term2/'

Best Answer

You could run sed without -i and step through output with less

grep -rl --null term1 . | xargs -0 sed -e 's/term1/term2/' | less

Then run sed with -i.bak to create backups which you can diff afterwards

grep -rl --null term1 . | xargs -0 sed -i.bak -e 's/term1/term2/'
diff somefile.bak somefile
# verify changes were correct

Edit: As suggested in comment, use grep --null | xargs -0. This causes filenames to be terminated by the null-byte, which makes it safe for filenames with unusual characters like newline. Yes, \n is a valid character in a unix filename. The only forbidden characters are slash / and the nul character \0

Related Question