gaspero1
gaspero1

Reputation: 129

How do I prepend a character to a field in a csv using awk

I am trying to prepend a single character to the beginning of a quoted csv file that looks like this:

"a","b","c","d","e","f","g","h"

The output I need would look like this:

"a","b","c","d","e","Nf","g","h"

Using the following awk command:

awk -F '{ $6="N" $6 }1' file.csv

I get the following close, but incorrect result:

"a","b","c","d","e",N"f","g","h"

How do I write an awk command that will correctly prepend a character inside the quoted text of a given field?

Upvotes: 2

Views: 197

Answers (4)

Dwayne Smith
Dwayne Smith

Reputation: 77

awk one liner

awk 'BEGIN{FS=OFS=","} {sub(/"/,"\"N",$6)}1' f1
"a","b","c","d","e","Nf","g","h"

Upvotes: 1

karakfa
karakfa

Reputation: 67567

with GNU sed

$ sed 's/,"/,"N/5' file

"a","b","c","d","e","Nf","g","h"

do the replacement after 5th comma, that is 6th field.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204721

$ awk 'BEGIN{FS=OFS="\",\""} {$6="N"$6} 1' file
"a","b","c","d","e","Nf","g","h"

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

With awk's sub() function:

awk 'BEGIN{ FS=OFS="," }{ sub(/"/, "&N", $6) }1' file.csv

The output:

"a","b","c","d","e","Nf","g","h"

Or with substr() function:

awk 'BEGIN{ FS=OFS="," }{ $6="\042N"substr($6, 2) }1' file.csv

Upvotes: 1

Related Questions