LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   incremental and selective line numbering (https://www.linuxquestions.org/questions/programming-9/incremental-and-selective-line-numbering-863770/)

harkonen 02-19-2011 02:13 PM

incremental and selective line numbering
 
I'm really close to getting this right, I think, but is one nuance eluding me, so I'm going to ask here.

I'm trying to number lines in a file -- but ONLY certain lines. Example:

Code:

bash$ cat file.txt
1 important line
  blah blah blah
2 important line
  blah blah blah
3 important line
  etc etc etc

I seem to be able to get sed and awk to grab only the important lines and number them, but I can't re-integrate those lines back into the file; ergo, I get:

Code:

bash$ cat file.txt | sed '/\<important/!d' | awk '{gsub(/\<important/,(x +=1));print}'
1 important line
2 important line
3 important line

I can also get sed alone to print the actual line numbers on just the important lines, but they obviously are the real line numbers and I'd prefer them to be numbered 1-whatever, sequentially, regardless of where they actually fall in the document.

Any ideas? I'm not married to sed or awk, so if it's a perl command or something, that works too.

Birei 02-19-2011 03:08 PM

Hi,

Tell if next 'perl' script can be useful to you.
Code:

$ cat infile
important line
blah blah blah
important line
blah blah blah
important line
etc etc etc
$ perl -ne 'BEGIN { $i = 0 } if ( /important/ ) { print ++$i, " ", $_ }' infile
1 important line
2 important line
3 important line

Regards,
Birei

harkonen 02-19-2011 03:19 PM

that's a great perl script to know about but unfortunately no that will not work, because (and I should have mentioned this in my first post) the important files happen at irregular intervals. Sometimes they are 3 lines apart, other times they will be 24 lines apart, and another time they might be 8 lines apart, and so on.

My advantage is that the important lines always will have a very easy-to-match regex in them. Finding them is easy; getting them numbered the way I want..that's the hard part!

colucix 02-19-2011 03:39 PM

Code:

awk '/important/{c = ++_}!/important/{c = ""}{printf "%3s ", c}1' file

harkonen 02-19-2011 03:55 PM

DONE!
 
Quote:

Originally Posted by colucix (Post 4264171)
Code:

awk '/important/{c = ++_}!/important/{c = ""}{printf "%3s ", c}1' file

If i'm ever in Bologna I'll buy you a coffee. This did it. Thanks a million!

colucix 02-19-2011 03:57 PM

You're welcome! So waiting for you in Bologna! ;)

Birei 02-19-2011 04:01 PM

Hi,

My script was incorrect. I missunderstood your question. This should do the job, although colucix already got it.
Code:

$ perl -ne 'BEGIN { $i = 0 } if ( /important/ ) { printf "%4d %s", ++$i, $_ } else { printf "    %s", $_ }' infile
Regards,
Birei


All times are GMT -5. The time now is 11:48 PM.