Skip to content
 

Quickly search and replace string with Regular expression in multiple files using perl

for i in *; do perl -p -w -e \’s/a(.*)b.*/d$1e/g\’  $i > temp/$i; done

for i in *; do perl -pi -w -e \’s/a(.*)b.*/d$1e/g\’  $i ; done

The first one can be used when you want to preserve the original file. The redirection will cause the file with replaced string to be written to the new location in the temp directory. Modify the same according to your needs.

The second can be used to modify the files in-line. Causing overwriting the original file.

Explanation of the RE : s/a(.*)b.*/d$1e/g

s – substitue

s(.*)b.* –> match anything starting with and store the substring upto b into $1 for further use. Continue matching from b until end of line

d$1e –> replace the original string with d concatened with $1 from the match above and then with e.

Sphere: Related Content

Technorati Tags: matching, multiple files, perl, RE, regular expression, replace

  • http://lindesk.com/ Binny V A

    perl -pi -e ‘s/OLD_TEXT/NEW_TEXT/g’ *.txt

    is enough – you don’t need the for loop.

  • http://amit-agarwal.co.in/ Amit Agarwal

    Agreed. It was taken from some other script, where I was doing some checking before replacing and did not change the same. My mistake.

  • http://amit-agarwal.co.in/ Amit Agarwal

    Agreed. Took the part from another script and forgot to remove the for part. Basically I was doing some checks before replacing the text.