Find and replace the line, and also set the counter in replacements

I have a bunch of files containing the same log message. One of them happens, but since the messages are identical, I don’t know which one. What I want to do is add a number after all these messages to distinguish them.

Now that I have a bunch search and a replacement to execute, I just write a quick single-line perl, for example:

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

But how can I insert a counter in replacements?

+5
source share
4 answers

You can use the eregex modifier to add the current 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
+8
source

This does the trick for me:

perl -pi -e 's/one/"replacement".$counter++/ge' *.c
+4

, BEGIN ( , ).

perl -p -e 'BEGIN {$ctr =99;} s/searched/replaced$ctr/; ++$ctr;' file
+2

EDIT: OOPS This can only be useful if your main project is also in perl.

This is probably somewhat offtopic, but how do I add automatic location to log messages? For instance,

sub whereami {
    my $shout = shift;
    my @stack = caller(1);
    print LOG "$stack[1]:$stack[2]: $shout\n";
}

(see perldoc caller)

Or even better use Log::Log4perl qw/:easy/;- it may be too much, but worth a try.

+1
source

All Articles