Role of output separator in print statement

When we print multiple fields separated by comma using print command, it uses OFS and ORS built-in variable values to decide how to print the fields and rows. Output field separator is stored in the OFS variable and output record separator is stored in the ORS variable. By default OFS is set to single space and ORS is set to a single newline. We can change these values anytime as required, but the usually best place to assign new values to OFS and ORS is in the BEGIN statement. For example, in the following example we print all the fields of car database with a colon between them as separator, and the two newlines after each processing record as follows:

$ vi output_separator.awk

BEGIN { OFS = ":"
ORS = " "
}
{ print $1,$2,$3,$4,$5 }

$ awk -f output_separator.awk cars.dat

The output on execution of the preceding code is as follows:

maruti:swift:2007:50000:5

honda:city:2005:60000:3

maruti:dezire:2009:3100:6

chevy:beat:2005:33000:2

honda:city:2010:33000:6

chevy:tavera:1999:10000:4

toyota:corolla:1995:95000:2

maruti:swift:2009:4100:5

maruti:esteem:1997:98000:1

ford:ikon:1995:80000:1

honda:accord:2000:60000:2

fiat:punto:2007:45000:3

We can also modify the values of OFS and ORS using the -v command-line option before the names of input files in the awk command. For example, we achieve the same output as in the previous example using the -v command-line option for setting OFS to colon and ORS to double newlines:

$ awk -v OFS=":" -v ORS="

" '{print $1,$2,$3}' cars.dat

The output on execution of the preceding code is as follows:

maruti:swift:2007

honda:city:2005

maruti:dezire:2009

chevy:beat:2005

honda:city:2010

chevy:tavera:1999

toyota:corolla:1995

maruti:swift:2009

maruti:esteem:1997

ford:ikon:1995

honda:accord:2000

fiat:punto:2007
printf doesn't use the OFS and ORS variables. It uses only the specified format specifier to print the field values and to separate them; we have to use escape sequences to format the output as desired.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86