Operating System - HP-UX
1760365 Members
4117 Online
108893 Solutions
New Discussion юеВ

how to add line no. to each line

 
SOLVED
Go to solution
emily_3
Frequent Advisor

how to add line no. to each line

Can anyone tell me.
How to add the line number to each line of a file? For example, i want to convert file1 to file2. Is there any command or have to write a script?

#vi file1
aaaaa
bbbbb
ccccc

#vi file2
1;aaaaa
2;bbbbb
3;ccccc
Thanks.
Regards.
7 REPLIES 7
Ermin Borovac
Honored Contributor
Solution

Re: how to add line no. to each line

Here is one liner in perl.

$ perl -p -e 's/^/$.;/' file1 > file2
Rajeev  Shukla
Honored Contributor

Re: how to add line no. to each line

Here, try with sed

sed = |sed 'N; s/\n/\;/'

Cheers
Rajeev
A. Clay Stephenson
Acclaimed Contributor

Re: how to add line no. to each line

Even easier and yes, there is a command. Use the nl command and specify a separator:

nl -s ';' file1 > file2

Man nl for details.
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: how to add line no. to each line


Cool Clay! I never knew that 'nl' command whereas I have it on a big sticker on the back of my car!

[(nl) - being the country 'plate' for the NetherLands]

If you have other things to do in the conversion/processing then an other weapon of choice might be awk:

awk '{print NR ";" $0}' file1 > file2


Hein.


emily_3
Frequent Advisor

Re: how to add line no. to each line

Thanks all of your contribution, i will try in different ways.
Sanjay Kumar Suri
Honored Contributor

Re: how to add line no. to each line

If the purpose is to view lines number along with each line, then it can be done in vi itself by the following

Esc
:nu



sks
A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.
H.Merijn Brand (procura
Honored Contributor

Re: how to add line no. to each line

nl is a strange command, since, imho, it works counterintuitive, because it numbers by default only non-blank lines. In fact, 'nl' never does what I want, and I always use 'pr' instead

I miss, next to nl, the obvious 'pr' command in the mentioned list

# pr -t -n\;4 -w9999 file

# nl -s\; -ba -n file

are almost the same. Please check if nl did not add empty lines on page breaks.

The other solutions are much better, since they number all lines, don't add formatting to the page numbers, and just do what you want

# perl -pe's/^/$.;/' file

# awk '{print NR ";" $0}' file

# sed = file | sed 'N; s/\n/\;/'

I don't like the sed command, because it adds and removes lines, but it works evenly well

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn