awk – Add a double quote to a string if it doesnt start with a double quote

awk – Add a double quote to a string if it doesnt start with a double quote

Following awk may help you here.

awk BEGIN{FS=OFS=,} $3 !~ /^/{$3= $3} 1  Input_file

OR

awk BEGIN{FS=OFS=,} {$3=$3 !~ /^/? $3:$3} 1  Input_file

EDIT: As per sir Jonathans comments in comment section adding following code which will handle 3 cases now, it should add is it not on 3rd field completely, it will add at last of field or starting of field too.

Lets say we have following Input_file:

cat Input_file
1,a,some strings in a pair of double quotes
2,b,more strings in a pair of double quotes
3,c,some messy strings with only right half double quotes
4,d,more strings in a pair of double quotes
4,d,more strings in a pair of double

now following code may cover all 3 mentioned permutations/combinations here:

awk BEGIN{FS=OFS=,} {$3=$3 !~ //? $3 :($3 !~ /^/? $3:($3 !~ /$/?$3 :$3))} 1  Input_file
1,a,some strings in a pair of double quotes
2,b,more strings in a pair of double quotes
3,c,some messy strings with only right half double quotes
4,d,more strings in a pair of double quotes
4,d,more strings in a pair of double

The problems with your addQuote() function:

function addQuote(input) {
 return  + input
}

are that:

  1. the string delimiter is , not so you should be using instead of .
  2. the + is an arithmetic operator in awk so + input is telling awk to convert both and the contents of input to numbers and then add them together. What you want instead is concatenation and there is no specific operator for that in awk – two strings side by side are concatenated, e.g. “ input`.

So if you wrote your function as:

function addQuote(input) {
 return ( input)
}

itd do what you want. I added the parens for readability.

Having said that, this might be a better approach as it covers missing quotes at the front and/or the back and ensures that EVERY line gets recompiled which is important if you ever change the OFS value: borrowing the input from @RavinderSing13s answer:

$ awk BEGIN{FS=OFS=,} {gsub(/^|$/,,$3); $3= $3 } 1 file
1,a,some strings in a pair of double quotes
2,b,more strings in a pair of double quotes
3,c,some messy strings with only right half double quotes
4,d,more strings in a pair of double quotes
4,d,more strings in a pair of double

awk – Add a double quote to a string if it doesnt start with a double quote

Leave a Reply

Your email address will not be published. Required fields are marked *