Dmitry
Dmitry

Reputation: 493

How do I add a line number to a file?

The contents of file.txt:

"16875170";"172";"50"
"11005137";"28";"39"
"16981017";"9347";"50"
"13771676";"13";"45"
"5865226";"963";"28"

File with the result:

"1";"16875170";"172";"50"
"2";"11005137";"28";"39"
"3";"16981017";"9347";"50"
"4";"13771676";"13";"45"
"5";"5865226";"963";"28"

Upvotes: 2

Views: 95

Answers (4)

Thor
Thor

Reputation: 47189

There is also coreutils nl:

<file.txt nl -s';' -w1 | sed 's/[0-9]*/"&"/'

Or perl:

<file.txt perl -pne 's/^/"$.";/'

Or sed and paste:

<file.txt sed = | paste -d\; - - | sed 's/[0-9]*/"&"/'

Output in all cases:

"1";"16875170";"172";"50"
"2";"11005137";"28";"39"
"3";"16981017";"9347";"50"
"4";"13771676";"13";"45"
"5";"5865226";"963";"28"

Upvotes: 0

Yunnosch
Yunnosch

Reputation: 26753

For the fun of sed:

sed "=" test.txt | sed "N;s/\([0-9]\{1,\}\)\n/\"\1\";/"

Output:

"1";"16875170";"172";"50"
"2";"11005137";"28";"39"
"3";"16981017";"9347";"50"
"4";"13771676";"13";"45"
"5";"5865226";"963";"28"

Upvotes: 1

eftshift0
eftshift0

Reputation: 30297

also, bash-based:

i=0; cat my_file.txt | while read line; do i=$(( $i + 1 )); echo \"$i\"\;"$line"; done > results.txt

Upvotes: 0

zzevannn
zzevannn

Reputation: 3724

awk can do this for you pretty easily.

$ cat test.txt
"16875170";"172";"50"
"11005137";"28";"39"
"16981017";"9347";"50"
"13771676";"13";"45"
"5865226";"963";"28"

$ awk '{print "\""NR"\";"$0}' test.txt
"1";"16875170";"172";"50"
"2";"11005137";"28";"39"
"3";"16981017";"9347";"50"
"4";"13771676";"13";"45"
"5";"5865226";"963";"28"

This tells awk to print a literal ", followed by the record number, followed by ";, then rest of the line. Depending on other needs not stated (e.g. the quoting not being totally necessary,) there may be a better method to use but given the question and output this works.

Grep solution for funsies:

$ grep ".*" test.txt -n | sed 's/\([0-9]*\):/"\1";/g;'
"1";"16875170";"172";"50"
"2";"11005137";"28";"39"
"3";"16981017";"9347";"50"
"4";"13771676";"13";"45"
"5";"5865226";"963";"28"

Upvotes: 6

Related Questions