Search code examples
perlawksed

insert quotes for each field using awk


I am looking for below input based on the sample provided below

Sample :

eno~ename~address~zip
123~abc~~560000~"a~b~c"
245~"abc ~ def"~hyd~560102
333~"ghi~jkl"~pub~560103

Expected output :

"eno"~"ename"~"address"~"zip"
"123"~"abc"~""~"560000"~"a~b~c"
"245"~"abc ~ def"~"hyd"~"560102"
"333"~"ghi~jkl"~"pub"~"560103"

command which i tried in awk it doesn't work if the delimiter value contains in data. If there are any alternate suggestions with perl/sed/awk suggest.

Below is the command : awk '{for (i=1;i<=NF;i++) $i="\""$i"\""}1' FS="~" OFS="~" sample


Solution

  • Here you can use FPAT with gnu awk

    awk -v FPAT='([^~]*)|("[^"]+")' -v OFS="~" '{for (i=1;i<=NF;i++) if ($i!~/^\"/) $i="\""$i"\""} 1' file
    "eno"~"ename"~"address"~"zip"
    "123"~"abc"~""~"560000"
    "245"~"abc ~ def"~"hyd"~"560102"
    "333"~"ghi~jkl"~"pub"~"560103"
    

    Instead of telling how the Field Separator looks like, we tell how the filed looks like. Then test if field not has double quote, if no, add it.

    You can then easy change the Field Separator if you like:

    awk -v FPAT='([^~]*)|("[^"]+")' -v OFS="," '{for (i=1;i<=NF;i++) if ($i!~/^\"/) $i="\""$i"\""} 1' file
    "eno","ename","address","zip"
    "123","abc","","560000"
    "245","abc ~ def","hyd","560102"
    "333","ghi~jkl","pub","560103"