Tuesday, October 25, 2022

[SOLVED] Add continuous numbers to each row if contains string

Issue

I have some variables like this:

_
C
E
_
N
B
_
_

I want to add numbers to each row if it isn't "_". The output should look like this:

_ 
C 1
E 2
_
N 3
B 4
_
_

" _ " could appear in any position, not only at the start or end. And, the first row is not always " _ ".

I have no clue to do this. That would be very nice If anyone could guide me. Thanks!


Solution

Perl to the rescue!

perl -pe 's/$/" " . ++$i/e unless /_/' file
  • -p runs the code for each line and prints the output after processing;
  • s/PATTERN/REPLACEMENT/ is a substitution. Here, the pattern is $ which matches at the end of a string, before the final newline if any;
  • The /e modifier of the substitution interprets the replacement as code. Here, the code is " " . ++$i, i.e. a concatennation of a space and a the number that you get when you increment a variable that starts at 0;
  • The substitution is only run on lines not containing a underscore.


Answered By - choroba
Answer Checked By - Mary Flores (WPSolving Volunteer)