replace character with increasing numbers per line

111 views Asked by At

I have large matrix files consisting of only "0" and "a" in clolumns and I want to do what this does:

perl -pe 'BEGIN { our $i = 1; } s/a/($i++)/ge;'; < FILE > NEW_FILE

but only increment once for each line instead of every instance on each line.

So if my first line in the file is:

0 0 a a a

The perl command gives me:

0 0 1 2 3

While i would want

0 0 1 1 1 

and on the next line for instance 2 0 2 0 2 and so on...

This should be possible to do with awk, but using:

'{ i=1; gsub(/a/,(i+1));print}' tmp2 

just gives me 0's and 2's for all lines...

3

There are 3 answers

0
Borodin On

You can simply replace every occurrence of a with the current line number

perl -pe 's/a/$./g' FILE > NEW_FILE
1
fedorqui On

Just increment before, not on every substitution:

awk '{i++; gsub(/a/,i)}1' file

This way, the variable gets updated once per line, not once per record.

The same applies to the Perl script:

perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' file

Test

$ cat a
0 0 a a a
2 3 a a a
$ awk '{i++; gsub(/a/,i)}1' a
0 0 1 1 1
2 3 2 2 2
$ perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' a
0 0 1 1 1
2 3 2 2 2
0
Hynek -Pichi- Vychodil On
perl -pe'$i++;s/a/$i/g'

or if you like to increment only for lines with any substitution

perl -pe'/a/&&$i++;s/a/$i/g'

In action:

$ cat a
0 0 a a a
1 2 0 0 0
2 3 a a a
$ perl -pe'$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 3 3 3
$ perl -pe'/a/&&$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 2 2 2