JPT
JPT

Reputation: 555

Regex for Replacing String with Incrementing Number

Once upon a time I used UltraEdit for making this

text 1
text 2
text 3
text 4
...

from that

text REPLACE
text REPLACE
text REPLACE
text REPLACE
...

it was as easy as replace REPLACE with \i

now, how can I do this with eg. sed?

If you provide a solution, could you please add directions for filling the result with leading zeros?

thanks

Upvotes: 3

Views: 2969

Answers (3)

glenn jackman
glenn jackman

Reputation: 247250

perl -i -pe 's/REPLACE/++$i/ge' file

For zero-padding to the minimum width (i.e. if there are 10 replacements, use field width 2):

perl -i -pe '
    BEGIN {
        $patt = "REPLACE"; 
        chomp( $n = qx(grep -co "$patt" file) ); 
        $n = int( log($n)/log(10) ) + 1;
    } 
    s/$patt/ sprintf("%0*d", $n, ++$i) /ge
' file

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204731

Is this what you want?

$ awk '{$NF=sprintf("%05d",++i)} 1' file
text 00001
text 00002
text 00003
text 00004

If not, edit your question to show some more truly representative sample input and expected output (and get rid of the ...s if they don't literally exist in your input and output as they make your example non-testable).

Upvotes: 1

anubhava
anubhava

Reputation: 786359

You can use awk instead of sed for this:

awk '{ sub(/REPLACE/, ++i) } 1' file
text 1
text 2
text 3
text 4
...

Code Demo

Upvotes: 3

Related Questions