I have code in which I need to do a mass find and replace (within only one file).

I need to do the following with over a hundred items:


Random code in between.

More random code...

100 more "begin()"s...



Random code in between.

More random code.

100 more "begin()"s...

perl -pe 's/begin\(/$&. ++$n/ge' < input-file

Or for in-place editing (that is replace the file with the modified copy of itself):

perl -pi.back -e 's/begin\(/$&. ++$n/ge' input-and-output-file

(remove the .back if you're feeling adventurous and don't need a backup).

The above replaces ever begin( with the same ($&) with the incremented value of the $n variable (++$n) appended (.).

If you want to replace begin() instead of begin(:

perl -pe 's/begin\(\K\)/++$n.")"/ge' < input-file
  • Thank you, but sorry, I'm confused, 1. What's in-place editing? 2. so how would I find and replace within the file "home/user/testing.txt". – Matthew D. Scholefield Aug 13 '13 at 17:17
  • 1
    @RandomPerson323 in-place editing means that instead of reading one file and writing to stdout, perl will edit the input file. The .back part makes a backup of the file with the extension .back. See man perlrun for more. – derobert Aug 13 '13 at 17:19
  • @derobert technically it doesn't edit in place, but it looks that way to the user. – jordanm Aug 13 '13 at 17:59
  • @jordanm Indeed, it's actually done with a temp file and a rename, as documented in the man page. – derobert Aug 13 '13 at 18:35
  • 2
    @RandomPerson323, replace input-and-output-file with home/user/testing.txt. – Stéphane Chazelas Aug 13 '13 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.