Linux – How to Prefix a column values with an apostrophe ( ‘ )

awkcsvlinuxsed

I have a CSV file with multiple columns and 1000's of records, I need to prefix all the values of one of the columns (lets say 2nd column) with an apostrophe ' except in the first line or header line, There might be an easy one liner for this. How could I achieve this using awk or sed? Please note, I might have multiple commas in the values which are enclosed in double quotes.

Sample data:

"col1","col2","col3","col4","col5"
"value11","value12","value13","value14","value15"
"value21","value22","value23","value24","value25"
"value31","value32","value33","value34","value35"

Expected output:

"col1","col2","col3","col4","col5"
"value11","'value12","value13","value14","value15"
"value21","'value22","value23","value24","value25"
"value31","'value32","value33","value34","value35"

Best Answer

sed:

sed '2,$s/^\("[^"]*","\)/\1'"'"/ test.in

Using EREs to get rid of some of the escaping:

sed -E '2,$s/^("[^"]*",")/\1'"'"/ test.in

awk:

awk -F, 'NR>1{sub(/^"/,"\"'"'"'",$2)}1' test.in

If you don't want to worry about the quoting, use the escape code:

awk -F, '{sub(/^"/,"\"\x27",$2)}1' test.in
Related Question