24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

record1<br />

record2<br />

data1<br />

data2<br />

kelly@octarine ~/test> awk '{ print $1 $2}' test<br />

record1data1<br />

record2data2<br />

kelly@octarine ~/test> awk '{ print $1, $2}' test<br />

record1 data1<br />

record2 data2<br />

kelly@octarine ~/test><br />

If you don't put in the commas, print will treat the items to output as one argument, thus omitting the use of<br />

the default output separator, OFS.<br />

Any character string may be used as the output field separator by setting this built-in variable.<br />

6.3.2.2. The output record separator<br />

The output from an entire print statement is called an output record. Each print command results in one<br />

output record, and then outputs a string called the output record separator, ORS. The default value for this<br />

variable is "\n", a newline character. Thus, each print statement generates a separate line.<br />

To change the way output fields and records are separated, assign new values to OFS and ORS:<br />

kelly@octarine ~/test> awk 'BEGIN { OFS=";" ; ORS="\n-->\n" } \<br />

{ print $1,$2}' test<br />

record1;data1<br />

--><br />

record2;data2<br />

--><br />

kelly@octarine ~/test><br />

If the value of ORS does not contain a newline, the program's output is run together on a single line.<br />

6.3.3. The number of records<br />

The built-in NR holds the number of records that are processed. It is incremented after reading a new input<br />

line. You can use it at the end to count the total number of records, or in each output record:<br />

kelly@octarine ~/test> cat processed.awk<br />

BEGIN { OFS="-" ; ORS="\n--> done\n" }<br />

{ print "Record number " NR ":\t" $1,$2 }<br />

END { print "Number of records processed: " NR }<br />

kelly@octarine ~/test> awk -f processed.awk test<br />

Record number 1: record1-data1<br />

--> done<br />

Record number 2: record2-data2<br />

--> done<br />

Number of records processed: 2<br />

--> done<br />

kelly@octarine ~/test><br />

Chapter 6. The GNU awk programming language 75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!