1

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

H-H
  • 374
  • 7
  • 14
  • 1
    The problem that the answers address without actually explaining, is that you have used double quotes which expand shell variable(which start with `$`, also if you look where the double qoutes are then you will notice the comma is not quoted, meaning it is seen by `awk` as a comma which is in turn represents the `OFS`(space). –  Dec 02 '14 at 08:29
  • Just use single quotes: `awk '{print NR "," $0}' file`. – fedorqui Dec 02 '14 at 08:36

5 Answers5

1

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.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

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
Community
  • 1
  • 1
H-H
  • 374
  • 7
  • 14
0

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
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
0

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
fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

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
Jotne
  • 40,548
  • 12
  • 51
  • 55