0

I have the following command to find and replace from the current directory tree down, "OldString" with "NewString".

sed -i 's/OldString/NewString/g' `grep -ril 'OldString' *`  

Can anybody advise how I might direct the output of this to a file, for verification:- The output file would then show the parent files + filepaths of which files were modified?

e.g. output file:

/home/htdocs/index.html 
/home/htdocs/file_containing_oldString.html
4
  • What about for file in $(grep -ril 'OldString'); do sed -i 's....g' $file; done ?
    – fedorqui
    May 8, 2014 at 12:41
  • Hi @fedorqui, would you mind directing this as an answer?
    – Barney
    May 8, 2014 at 12:44
  • To be clear - "OldString" is NOT a string, it's a regexp. Thinking of it as a string can/will bite you.
    – Ed Morton
    May 8, 2014 at 12:56
  • 1
    Hi Barney, I think @EdMorton 's answer is pretty pretty more powerful than my comment!
    – fedorqui
    May 8, 2014 at 13:08

1 Answer 1

3

The UNIX command to find files is named find, not grep. The GNU guys screwed up royally when they added that -r option. To find & replace a regexp with a string would be:

tmp=/usr/tmp/tmp$$
trap 'rm -f "$tmp"; exit' 0
find . -type f -print |
while IFS= read -r file
do
    sed 's/OldRegexp/NewString/g' "$file" > "$tmp" &&
    mv "$tmp" "$file"
done

The only caveat with that is it won't work if your file names contain newlines - if they do then either rename them (preferably) or look at find -print0 and xargs -0.

You can get rid of explicitly naming the tmp file by using sed -i if you prefer.

Now, if you want a list of which files were changed, you can just do something like:

tmp=/usr/tmp/tmp$$
trap 'rm -f "$tmp"; exit' 0
> logfile
find . -type f -print |
while IFS= read -r file
do
    sed 's/OldRegexp/NewString/g' "$file" > "$tmp"
    if [ $? -eq 0 -a diff -q "$tmp" "$file" ]
    then
        printf "%s\n" "$file" >> logfile
        mv "$tmp" "$file"
    fi
done

If you decide to use sed -i (personally, I wouldn't) then create the tmp copy of the file before the sed and use that for the diff.

3
  • Is it working fine? I suspected that using find ... | while ... would make the while block not to have access to $tmp as it is opening a new shell. If that was the case (I haven't tested), I would suggest to do while ... done < $(find ...)
    – fedorqui
    May 8, 2014 at 13:21
  • 1
    The loop will have access to the variable $tmp, it just wouldn't be able to change it outside of the context of the subshell.
    – Ed Morton
    May 8, 2014 at 13:23
  • 1
    +1 for royal screw up. Lemme get some napkin to wipe coffee off my screen. May 8, 2014 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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