Simpler Navigation coming for Servers and Operating Systems
Coming soon: a much simpler Servers and Operating Systems section of the Community. We will combine many of the older boards, and you won't have to click through so many levels to get at the information you need. If you are looking for an older board and do not find it, check the consolidated boards, as the posts are still there.
Showing results for 
Search instead for 
Did you mean: 

script problem

Occasional Contributor

script problem

how can i put a number in front of each line in a given file?
Luciano Carvalho
Respected Contributor

Re: script problem


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

John Poff
Honored Contributor

Re: script problem


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.

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:

cat file |
while read line
echo $count $line

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 ""

$ cat -n
1 myline1
2 myline2
3 myline3

Vitaly Karasik_1
Honored Contributor

Re: script problem

you can do it with

pr -n


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