Saturday, August 25, 2012

Change text inside multiple files (command line)

I always forget these commands, and they are so useful.
The sed command to replace some text in a set of files:
     sed -e 's/old text/new text/g'  -i .trash  *.c 

The regular expression 's/some text/new text/g' is applied to each line of each file *.c.
And the -i flag saves a backup of each file.

The regular expression language is powerful, for instance allows to remember parts of the pattern in the substitution. An example: the following command puts quotation marks around everything that follows the first = sign in each line of
  sed -e 's/=\(.*\)/="\1"/'

The pattern enclosed between \(   and   \) is stored in \1, and then used in the replaced text.


No comments:

Post a Comment