docs:bash:search_and_replace_in_files

grep -Z -R -l -E 'searchpattern' . | xargs -0 sed -i 's/searchpattern/replacestring/g'
  • :!: remember to escape parenthesis when using sed
  • this example finds all occurrences of 'oldhostname' where it is not followed by a period, and replaces it with 'newhostname'
grep -Z -R -l -E 'oldhostname[^\.]' . | xargs -0 sed -i 's/oldhostname\([^\.]\)/newhostname\1/g'
  • the -Z parameter was different for grep, so it actually wanted --null
  • the backup extension for sed was not optional, so '.sed' was used
grep --null -R -l -E 'oldhostname[^\.]' . | xargs -0 -t sed -i '.sed' 's/newhostname\([^\.]\)/xdev\1/g'
  • docs/bash/search_and_replace_in_files.txt
  • Last modified: 2009/06/03 10:45
  • by billh