Search code examples
awkoutputformat

AWK - Replacing Value Of Selected Column Destroys Output Format


I have a .csv file with the following format. id|name|date

I am using the following Awk command to change a specific column in a row and it works. awk -F "|" '{$"'"$col"'"="'"$val"'";}1' filename.csv

I wanna save the output , however the format is destroyed.

What I want : 100|James|2015

What I get : 100 James 2015

How do I avoid the second one, and get the first one ?


Solution

  • You could set the OFS, the Output Field Separator like in this example:

    awk -F\| -v OFS=\| '{print $1, $2, $3 }'  test.psv 
    
    • The -v OFS=\| assigns the OFS variable the values |. It is an alternative to a BEGIN { OFS = "|" } block.
    • The | needs to be protected from the shell, since the meaning an shell level is piping of one commands output into the input of another command. Using "|" or \| are two ways to do so.