Noobie
Noobie

Reputation: 55

Add incrementing numbers per line in UNIX

Hi all I'm new in scripting in UNIX and I'm trying to add incrementing numbers per line. For example i have sample.txt and inside sample.txt is

inside sample.txt:

Name1
Name2
Name3
..
..
.. 
Name26

and I want to make it look like this;

1Name1
2Name2
3Name3
..
..
.. 
26Name26

Thanks in advance.

Upvotes: 0

Views: 212

Answers (1)

Walter A
Walter A

Reputation: 20022

You said you do not want cat, but sample.txt edited.
It is a lot easier to find a solution with a temp file, something like cat, awk or (depending on the exact layout you want)

# grep with numbers every line, the dot for any character and * for possible 0 times
grep -n '.*' sample.txt ' > sample.txt.tmp && mv sample.txt.tmp sample.txt
# OR: 
# grep added a :, do want to delete it?
grep -n '.*' sample.txt | sed 's/://' > sample.txt.tmp && mv sample.txt.tmp sample.txt

When you make a script looping through the number of lines of the file (using wc) and call sed -i for each line you will have created a monster. sed -i will use a tmp file just as I did, but now for every line !

Upvotes: 1

Related Questions