H-H
H-H

Reputation: 456

Can't add a line number to the beginning of each line with awk

I'm trying this awk command awk "{print NR, $0}" file1.csv, but it's adding the line number followed by a space and not a comma.

I tried other commands with the same results

awk "{print NR "," $0}" file1.csv

And I have an error wherever I use a single quote.

I'm using Gawk on Windows. I'm I missing something?

Thank you

Upvotes: 1

Views: 129

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174776

Just include the awk's code inside single quotes instead of double quotes.

awk '{print NR "," $0}' file1.csv

OR

awk -v FS="," -v OFS="," "{print NR,$0}" file.csv

And your your previous command awk "{print NR, $0}" file1.csv displays space instead of comma because by default , in the print section will print the value of Output Field Separator variable . The default value of OFS is space by default. So it displays space instead of comma.

Upvotes: 1

Jotne
Jotne

Reputation: 41460

The , in your awk is the default Field Separator, one space.
To get what you want chnage the Output Field Separator.

awk -vOFS="," '{print NR, $0}' file1.csv

Upvotes: 0

H-H
H-H

Reputation: 456

Thank you all for your answers, but I found one that work: on window I have to escape inside double quotes:

awk "{print NR \",\" $0}" file1.csv

Upvotes: 1

fredtantini
fredtantini

Reputation: 16566

Using a comma like in "{print NR, $0}" you are printing each term following print with the field separator.

Using double quotes in awk "{print NR "," $0}" you are splitting the command with a comma.

You have to use single quotes for the whole awk command:

awk '{print NR","$0}' file1.csv

Or use the printf statement

awk '{printf("%s,$0\n", NR,$0)}' f

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

Try this:

awk '{print NR "," $0}' file1.csv

Example:

sdlcb@BlrLaite2-Generic:~$ cat ff
aa, aa, aa, aa
aa, aa, aa, aa
aa, aa, aa, aa
aa, aa, aa, aa
aa, aa, aa, aa
aa, aa, aa, aa
sdlcb@BlrLaite2-Generic:~$ awk '{print NR "," $0}' ff
1,aa, aa, aa, aa
2,aa, aa, aa, aa
3,aa, aa, aa, aa
4,aa, aa, aa, aa
5,aa, aa, aa, aa
6,aa, aa, aa, aa

Upvotes: 0

Related Questions