How to add line numbers (multiples of 5: 0,5,10,15,20) to a text file?

Hi,

I need to number the lines in my text file. I know how to do this with standard numbering (1,2,3,4, etc) but I need to count in multiples of 5, beginning 0,5,10,15...

example existing file:

abcd
efg
hijklm
nopqrs

desired output

0        abcd
5       efg
10    hijklm
15    nopqrs

etc.

Please advise. Can I use awk? Crucially it MUST begin with 0!

Thanks in advance.:stuck_out_tongue:

Hello,

Could you please use code tage as per the forum rules.
Here is the solution that may help you.

awk 'NR==1{i=0} {print i " "$0} {i=i+5}' check_file_count5

Output will be as follows.

0 abcd
5 efg
10 hijklm
15 nopqrs

Thanks,
R. Singh

Thank you so much! I apologise for my misuse of the code tags.

Try also

awk '{print (NR-1)*5, $0}' file
0 abcd
5 efg
10 hijklm
15 nopqrs

or

awk '$0=(NR-1)*5" " $0' file

On Linux:

nl -v 0 -i 5 file
1 Like

Also if required, add -n option to format (ln - left justified, leading zeroes suppressed):

nl -v0 -i5 -nln file

Hello Yoda,

Could you please explain the code.

Thanks,
R. Singh

man nl ?

Thanks RudiC, I have gone through the man page for nl
and able to understand the command now.

-v Number
            Sets the initial logical-page line number to the value specified by the Number variable. The default value of the Number variable is 1. The range of the
            Number variable is from 0 to 32767.
-i Number
            Increments logical-page line numbers by the number specified in the Number variable. The default value of the Number variable is 1. The range of the
            Number variable is from 1 to 250.
-n Format
            Uses the value of the Format variable as the line numbering format. Recognized formats are:
              ln
                   Left-justified, leading zeros suppressed

Thanks,
R. Singh

Shedding a few more characters:

awk '$0=i++*5" "$0' file

There's a way to reduce it by at least one more character. Does anyone see it?

Regards,
Alister

awk '$0=i+=5" "$0' file

(not tested, I'm on my phone)

That won't work.

In that expression, string concatenation has highest precedence, so, firstly, 5" "$0 is joined. Then, while converting the just-concatenated string to a numeric, += truncates it at the first space, discarding the entire record, $0.

Your suggestion is equivalent to $0=i+=5 . Aside from the discarded data, this generates an arithmetic sequence which begins at 5, not 0.

Regards,
Alister