in reply to Perl substitute with the nth match
Can you? I can, too:
perl -pe 's/cat/++$i/ge' file
There's no special variable that counts matches. But there's one that's incremented with each line of input: $.. So if we could tell Perl that cat instead of a newline is the line delimiter... but of course we can do that! That's what $/ is for.
perl -pe 'BEGIN { $/ = "cat" } chomp; $_ .= $. unless eof' file
Update: which can be rewritten to use substitution as you originally wanted:
perl -pe 'BEGIN { $/ = "cat" } s{$/}{$.}' file
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl substitute with the nth match
by LanX (Saint) on Jan 13, 2023 at 13:50 UTC |