Search code examples
awkline-endings

How to add quotes from specific delimiter to end of the line, using awk?


I am trying to modify a file: (file.txt)

abc~123~xyz~123456~12~0.12~14~1.1~  
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~

to (new_file.txt)

abc~123~xyz~123456~"12~0.12~14~1.1~"  
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

I tried using awk command:

awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt

but I am getting output as:

abc~123~xyz~123456~"12~0.12~14~1.1~~"  
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.


Solution

  • You have a ~ separator at the end of your lines. So, you have an extra empty field after this field separator. You can check this with:

    $ awk -F'~' '{print NF "|" $NF "|"}' file.txt
    9||
    13||
    

    See? When printing this last empty field followed by a ~, you simply concatenate it to the previous one, thus the ~~. Try:

    $ awk -F '~' -vOFS='~' '{$5 = "\"" $5; $NF = $NF "\""; print}' file.txt
    abc~123~xyz~123456~"12~0.12~14~1.1~"
    omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
    

    We just declare ~ as the input and output (with variable OFS) field separator, prepend a " to the fifth field, append one to the last field, and print.