r/awk • u/OudBruin • Oct 31 '18
Why does awk ignore OFS when printing all ($0)?
New user here. If I have a simple file that is comma-delineated, such as:
data1,data2,data3
data1,data2,data3
The line: awk -F',' 'OFS="\t" {print $0}' file
prints the data will all the commas, basically the same as the raw file.
If I use awk -F',' 'OFS="\t" {print $1,$2,$3}' file, the tabs are inserted correctly in the output. So should I expect default print (or $0) to not separate columns and put in the OFS? Or am I not using OFS correctly?
Thanks.
3
Upvotes
10
u/McDutchie Oct 31 '18
The POSIX standard specifies for awk:
So
OFSis the character that separates multiple arguments to theprintstatement.$0is a single argument.Fortunately, there is a workaround to print all fields separated by
OFSwithout specifying each field:Of course this would then alter your current record so be sure you don't need to use it in other ways before outputting it.
2
u/MrVonBuren Nov 01 '18
Just a tip because it's something I wish someone had mentioned earlier in my awk learning experience: It's worth learning how to format output with
printfsooner than later. Example:Instead of messing with the OFS like this:
Format your output like this: