9

I want to add a column (2nd place) in a .csv file and I want the values of that column to be strings and to be quoted;

The following command does add the column but without quotes:

awk -F"," 'BEGIN { OFS = "," } {$2="2.4.0"; print}' test.csv > output.csv

The following approach does incorporate the quotes, but for some reason it removes the last . (dot) from the value

awk -F"," 'BEGIN { OFS = "," } {$2="\""2.4.0"\""; print}' test.csv > output.csv

so my values end up being "2.40".

How should I go about this?

  • If your file have 2 or more columns, you want to insert or replace the second column ? – ctac_ Mar 4 at 9:27
  • just insert a column after the first one – pkaramol Mar 4 at 9:34
  • 2
    ok, so to insert, you must use : awk 'BEGIN{FS=OFS=","}{$1=$1",\"2.4.0\""}1' – ctac_ Mar 4 at 9:39
  • 1
    or awk '{sub(",",",\"2.4.0\",")}1' – ctac_ Mar 4 at 9:50
12

You seem to have got the quotes wrong. You need to do as below

awk -F"," 'BEGIN { OFS = "," } {$2="\"2.4.0\""; print}' test.csv > output.csv

This is explained in the GNU awk man page - 3.2 Escape Sequences

Some characters cannot be included literally in string constants ("foo") or regexp constants (/foo/). Instead, they should be represented with escape sequences, which are character sequences beginning with a backslash (\). One use of an escape sequence is to include a double-quote character in a string constant. Because a plain double quote ends the string, you must use \" to represent an actual double-quote character as a part of the string..


As far as the reason I could understand the reason for the behavior, awk seems to have interpreted 2.4.0 as a numeric word with the extra quotes from your OP and decides to lose the precision after the first dot.

i.e.

$2="\""2.4.0"\""

becomes just

$2=""2.4.0""

which awk no longer understands as a string. You can reproduce this behavior by simply doing

awk 'BEGIN { print ""2.4.0"" }'
2.40

which happens to be the result when you do

awk 'BEGIN { print 2.4.0 + 0 }'
  • 1
    @roaima: From what I've know, it seems to have just cancelled out and just resulting in { print 2.4.0 } or { print 2.4.0 + 0 }, i.e. as a non-string constituent. I've tried to search fro relevant docs too, but couldn't – Inian Mar 4 at 8:47
  • 2
    Another way of conveniently adding quotes that I sometimes use, is to define a variable, e.g.: awk -v q='"' '... print q "2.4.0" q ... – Thor Mar 4 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.