user2854333
user2854333

Reputation: 640

Add quotes to strings between commas shell

I have a string like

1,2,A,N,53,3,R,R,^A,-C,-T,2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P

Now, I am trying to achieve below string

1,2,A,N,53,3,R,R,"^A,-C,-T",2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P

So, I am trying to replace everything after 8th occurrence of comma (,) from start and before 12th occurrence of comman (,) from end to be in quotes.

I tried some options of awk but unable to achieve it . Anyway to get this done .

Thanks in advance .

Upvotes: 0

Views: 112

Answers (5)

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{sub(/\^A,-C,-T/,"\42^A,-C,-T\42")}1' file

1,2,A,N,53,3,R,R,"^A,-C,-T",2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P

The fine point here is to escape the caret.

Upvotes: 0

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed 's/,/&"/8;s/,/"&/11' file

Insert " after and before ' eight and eleven.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133770

try:

awk -v s1="\"" -F, '{$9=s1 $9;$(NF-12)=$(NF-12) s1} 1' OFS=,   Input_file

So here I am making a variable which is " and making field separator as comma. Then I am re-creating 9th field as per your requirement with s1 and $9. Then re-creating 13th field from last(point to be noted no hardcoding of field number here so it may have any number of fields) and adding s1's value in last of it's current value. Then mentioning 1 will print the line. Setting OFS(output field separator) as comma too.

Upvotes: 1

CWLiu
CWLiu

Reputation: 4043

$ awk -v FS=',' -v OFS=',' '{$9="\"" $9;$11=$11"\""; print}' your_file
1,2,A,N,53,3,R,R,"^A,-C,-T",2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P

Upvotes: 1

P....
P....

Reputation: 18411

x='1,2,A,N,53,3,R,R,^A,-C,-T,2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P'

awk -F, -v OFS=,  -v q='"' '{$9=q $9;$11=$11 q}1' <<< "$x"
1,2,A,N,53,3,R,R,"^A,-C,-T",2,S,9,l,8,8Z,sl,138Z,l,Y,75680,P

Explanation: Here FS and OFS are set to comma as the input stream is CSV.double quote is stored in a variable named q. Then the value of the desired columns are altered to get the desired results. You can change the values of columns to get any other results.

For files:

awk -F, -v OFS=,  -v q='"' '{$9=q $9;$11=$11 q}1' inputfile

Upvotes: 1

Related Questions