Monday, December 5, 2011

string find and replace in files

The -i option to sed does in place file editing, however it "modifies" each file it touches whether it actually does any replacing or not (so the file mod time is updated). By filtering through grep first, we can be sure we are only messing with files we actually want to. Replace "happy" with "blammo":
find . -type f -print0 | xargs -0 grep -lZ "happy" | xargs -0 sed -i 's/happy/blammo/g'
The -l option to grep prints file names only and stops with the first match (so no duplicates). -Z uses null byte for separator instead of newline.

No comments:

Post a Comment