Number some lines discard others?

Hi,
I'd like to do an operation on text with a format like this

this line shall be numbered
     this line shall not be numbered
this line shall also be numbered
     this line shall not not be numbered

And I want an output like this

1 this line shall be numbered
     this line shall not be numbered
2 this line shall also be numbered
     this line shall not not be numbered

nl numbers each line, and I can't seem to find a way for nl to discard lines beginning with spaces/tabs or any other specified set of characteristics.

Any solution is much appreciated. Thank you for reading!

Try:

awk '/^[^ \t]/{$0=++i" "$0}1' file
1 Like

Thank you. Just what I was looking for!

Can you please explain the usage of the 1 after the action ?

1 are always true. Give the same as {print $0}

1 Like

Please find the explanation given by Scrutinizer & Corona688 in this thread

1 Like

nl does have the ability to only number lines matching (basic) regex. But it still leaves extra spaces which may not be acceptable to you. Notice the alignment of the second and last line.

nl -s' ' -nln -b'p^[^ ]' -w1 file
1 this line shall be numbered
       this line shall not be numbered
2 this line shall also be numbered
       this line shall not not be numbered
1 Like