Reputation: 1335
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
Upvotes: 1
Views: 143
Reputation: 133538
Could you please try following(tested with provided samples only).
awk 'BEGIN{s1="\"";FS=OFS="~"} {for(i=1;i<=NF;i++){if($i!~/^\"|\"$/){$i=s1 $i s1}}} 1' Input_file
Output will be as follows.
"eno"~"ename"~"address"~"zip"
"123"~"abc"~""~"560000"
"245"~"abc ~ def"~"hyd"~"560102"
"333"~"ghi~jkl"~"pub"~"560103"
Explanation: Adding explanation for above code now.
awk ' ##Starting awk program here.
BEGIN{ ##Starting BEGIN section of awk program here.
s1="\"" ##Setting variable s1 to " here.
FS=OFS="~" ##Setting value of FS and OFS as ~ here.
} ##Closing BEGIN block of awk code here.
{
for(i=1;i<=NF;i++){ ##Starting for loop here from i=1 to till value of NF here.
if($i!~/^\"|\"$/){ ##Checking condition of value of current field is NOT having s1 value in it.
$i=s1 $i s1 ##Adding s1 variable before and after the value of $i.
} ##Closing block for if condition.
} ##Closing block for for loop here.
} ##Closing main block here.
1 ##Mentioning 1 will print the lines of Input_file.
' Input_file ##mentioning Input_file name here.
Upvotes: 2
Reputation: 41454
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"
Upvotes: 0