kriss
kriss

Reputation: 24207

Search and replace string and also put a counter in replacements

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 ?

Upvotes: 5

Views: 1640

Answers (4)

Happyblue
Happyblue

Reputation: 141

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

Upvotes: 2

Dallaylaen
Dallaylaen

Reputation: 5318

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.

Upvotes: 1

codaddict
codaddict

Reputation: 455312

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

Upvotes: 9

psmears
psmears

Reputation: 28080

This does the trick for me:

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

Upvotes: 4

Related Questions