Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the output field separator in awk

Tags:

shell

awk

I'n trying this statement in my awk script (in a file containing separate code, so not inline), script name: print-table.awk

BEGIN {FS = "\t";OFS = "," ; print "about to open the file"}
{print $0}
END {print "about to close stream" }

and running it this way from the shell

awk -f print-table.awk table

Where table is a tab separated file, My goal is to declare the field separator (FS) and the output field separator (OFS) within the external function, and calling from the shell simply the

awk -f file input

without setting the field separator in the command line with -F"\t" and without stdout it to a sed statement replacing the tab with a comma,

Any advise how can i do that?

like image 637
JBoy Avatar asked Dec 30 '13 17:12

JBoy


People also ask

How do I change the field separator in awk?

Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

What is output field separator in awk?

Any string of characters may be used as the output field separator by setting the predefined variable OFS . The initial value of this variable is the string " " (i.e., a single space). The output from an entire print statement is called an output record.

What is awk default field separator?

The default field delimiter or field separator (FS) is [ \t]+ , i.e. one or more space and tab characters.

How do you use delimiter in awk?

The AWK Field Separator (FS) is used to specify and control how AWK splits a record into various fields. Also, it can accept a single character of a regular expression. Once you specify a regular expression as the value for the FS, AWK scans the input values for the sequence of characters set in the regular expression.


1 Answers

You need to convince awk that something has changed to get it to reformat $0 using your OFS. The following works though there may be a more idiomatic way to do it.

BEGIN {FS = "\t";OFS = "," ; print "about to open the file"}
{$1=$1}1
END {print "about to close stream" }
like image 143
Etan Reisner Avatar answered Oct 04 '22 04:10

Etan Reisner