0

If I have a text file saying this:

Xgrep () { something ; }  

Xgrep
Xgrep
Xgrep
Xgrep
Xgrep

I want it to look like this

Xgrep () { something ; }  

Xgrep 12
Xgrep 13
Xgrep 14
Xgrep 15
Xgrep 16

Meaning I want to choose at which number to begin, with suffixes instead of prefixes with one space between (-s " " for a space between). I thought that I could use nl for this, but reading the man page it doesn't seem so. I tried this:

nl -b pexpr=Xgrep -s " " ~/desktop/test.txt

However this just out put this:

    Xgrep
    Xgrep
    Xgrep
    Xgrep
    Xgrep

Which is probably because the regex syntax is wrong but I couldn't find a way for it to match, all other ways it just listed the usage.

This website is pretty much exactly what I am trying to do, but in command line form and only with numbers suffix.

  • 1
    The syntax for the BRE match would be something like nl -b p'^Xgrep$' file or nl --body-numbering=p'^Xgrep$' file I think. However, I don't know that nl allows either RH placement (as opposed to right justification) or provision of a specific start index. If you aren't stuck on nl you could use something like awk -vi=12 '/^Xgrep$/ {$(NF+1)=i++}1' file – steeldriver Oct 3 '15 at 16:16
1
% perl -ple 'BEGIN{$i=12} s/^(Xgrep)\s*$/"$1 ".$i++/e' < in
Xgrep () blah

Xgrep 12
Xgrep 13
Xgrep 14
Xgrep 15
Xgrep 16
Xgrep 17
% 

Print lines, BEGIN the counter, match Xgrep and tack the incremented number onto the end. Replace < in with filename and add -i flag to clobber file in-place, if desired. An awk solution will likely look very similar.

  • Thanks! This works, but can I make the line to begin at a variable? – DisplayName Oct 3 '15 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.