1752694 Members
5926 Online
108789 Solutions
New Discussion юеВ

script problem

 
neocosmic
Occasional Contributor

script problem

how can i put a number in front of each line in a given file?
6 REPLIES 6
LucianoCarvalho
Respected Contributor

Re: script problem

hi,

when you are usign "vi" editor, you can use the "set number" command to numer each line of your file.

regards
John Poff
Honored Contributor

Re: script problem

Hi,

Here are some ways to do it in sed:

# number each line of a file (simple left alignment). Using a tab (see
# note on '\t' at end of file) instead of space will preserve margins.
sed = filename | sed 'N;s/\n/\t/'

# number each line of a file (number on left, right-aligned)
sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /'

# number each line of file, but only print numbers if line is not blank
sed '/./=' filename | sed '/./N; s/\n/ /'


Courtesy of Eric Pement's wonderful One Liners for Sed.

JP
John Meissner
Esteemed Contributor

Re: script problem

If you mean while you are vi'ing the file you can hit escape then ":" and type "set nu" This will number each line. if you want to add actual numbers into the file you can do this:

count=1
cat file |
while read line
do
echo $count $line
((count=$count+1))
done

if you want to save this output you can send it to another file and rename it back to the original if you so wish.
All paths lead to destiny
Jared Middleton
Frequent Advisor

Re: script problem

Here are a couple quick-and-dirty methods:

$ cat | grep -n ""
1:myline1
2:myline2
3:myline3

$ cat -n
1 myline1
2 myline2
3 myline3

-Jared
Vitaly Karasik_1
Honored Contributor

Re: script problem

you can do it with

pr -n

too

Regards,
Vitaly
Vitaly Karasik_1
Honored Contributor

Re: script problem

two more ways from my collegaus:

1) Tom Rosenfeld
And don't forget nl(1) the Number Line utility written for just this problem! try
$ nl files...
or see the man page for all the options.


2) Jonathan rodin
Just in case people get bored of using all the other ways, there's also:

less -N