Thursday 25 November 2010

Quick find and replace in bash across multiple files

I'm always trying to find easier ways of doing things, and here is a way (in BASH) that allows me to find and replace a line of text (ie. a string) across multiple files much quicker than opening up each file, and doing it manually:

for i in $(grep "String1" *|cut -d ":" -f 1); do
  sed "s/String1/String2/g" $i > $i.new;
  rm $i;
  mv $i.new $i;
done

1 comment:

  1. use the -i switch to sed and it will according to the man page:

    -i[SUFFIX]
    --in-place[=SUFFIX]
    This option specifies that files are to be edited in-place. GNU sed does this by creating a temporary file and sending output to this file rather than to the standard output.1.

    This option implies -s.

    When the end of the file is reached, the temporary file is renamed to the output file's original name. The extension, if supplied, is used to modify the name of the old file before renaming the temporary file, thereby making a backup copy.

    This rule is followed: if the extension doesn't contain a *, then it is appended to the end of the current filename as a suffix; if the extension does contain one or more * characters, then each asterisk is replaced with the current filename. This allows you to add a prefix to the backup file, instead of (or in addition to) a suffix, or even to place backup copies of the original files into another directory (provided the directory already exists).

    If no extension is supplied, the original file is overwritten without making a backup.

    ReplyDelete