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.

There are several ways to run awk. If the program is short, it is easiest to run it on the command line:<br />

awk PROGRAM inputfile(s)<br />

If multiple changes have to be made, possibly regularly and on multiple files, it is easier to put the awk<br />

commands in a script. This is read like this:<br />

awk -f PROGRAM-FILE inputfile(s)<br />

6.2. The print program<br />

6.2.1. Printing selected fields<br />

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

The print command in awk outputs selected data from the input file.<br />

When awk reads a line of a file, it divides the line in fields based on the specified input field separator, FS,<br />

which is an awk variable (see Section 6.3.2). This variable is predefined to be one or more spaces or tabs.<br />

The variables $1, $2, $3, ..., $N hold the values of the first, second, third until the last field of an input line.<br />

The variable $0 (zero) holds the value of the entire line. This is depicted in the image below, where we see<br />

six colums in the output of the df command:<br />

Figure 6-1. Fields in awk<br />

In the output of ls -l, there are 9 columns. The print statement uses these fields as follows:<br />

kelly@octarine ~/test> ls -l | awk '{ print $5 $9 }'<br />

160orig<br />

Chapter 6. The GNU awk programming language 70

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

Saved successfully!

Ooh no, something went wrong!