Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace string and also put a counter in replacements

Tags:

string

regex

perl

I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

perl -pi -e 's/searched/replacement/g' *.c

But how can I insert a counter in replacement ?

like image 450
kriss Avatar asked Dec 21 '10 11:12

kriss


1 Answers

You can use the e regex modifier to append a running counter value to your replacement as:

perl -pi -e 's/searched/"replacement".++$i/ge' *.c

Demo:

$ cat file
hi foo
hey foo
bye foo

$ perl -p -e 's/foo/"bar".++$i/ge' file
hi bar1
hey bar2
bye bar3
like image 75
codaddict Avatar answered Oct 13 '22 00:10

codaddict