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 thes开发者_开发技巧e 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 ?
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
This does the trick for me:
perl -pi -e 's/one/"replacement".$counter++/ge' *.c
If your counter needs initialization, put your initialization code in a BEGIN block (so it executes only once, at the start).
perl -p -e 'BEGIN {$ctr =99;} s/searched/replaced$ctr/; ++$ctr;' file
EDIT: OOPS This may only be helpful if your main project is in perl, too.
This is probably somewhat offtopic, but what about adding automagic location detection to the log messages? Like,
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 might be an overkill, but it's worth a try.
精彩评论