FS
from the Command Line
FS
can be set on the command line. You use the `-F' option to
do so. For example:
awk -F, 'program' input-files
sets FS
to be the `,' character. Notice that the option uses
a capital `F'. Contrast this with `-f', which specifies a file
containing an awk
program. Case is significant in command line options:
the `-F' and `-f' options have nothing to do with each other.
You can use both options at the same time to set the FS
variable
and get an awk
program from a file.
The value used for the argument to `-F' is processed in exactly the
same way as assignments to the built-in variable FS
. This means that
if the field separator contains special characters, they must be escaped
appropriately. For example, to use a `\' as the field separator, you
would have to type:
# same as FS = "\\" awk -F\\\\ '...' files ...
Since `\' is used for quoting in the shell, awk
will see
`-F\\'. Then awk
processes the `\\' for escape
characters (see section Escape Sequences), finally yielding
a single `\' to be used for the field separator.
As a special case, in compatibility mode
(see section Command Line Options), if the
argument to `-F' is `t', then FS
is set to the tab
character. This is because if you type `-F\t' at the shell,
without any quotes, the `\' gets deleted, so awk
figures that you
really want your fields to be separated with tabs, and not `t's.
Use `-v FS="t"' on the command line if you really do want to separate
your fields with `t's
(see section Command Line Options).
For example, let's use an awk
program file called `baud.awk'
that contains the pattern /300/
, and the action `print $1'.
Here is the program:
/300/ { print $1 }
Let's also set FS
to be the `-' character, and run the
program on the file `BBS-list'. The following command prints a
list of the names of the bulletin boards that operate at 300 baud and
the first three digits of their phone numbers:
$ awk -F- -f baud.awk BBS-list -| aardvark 555 -| alpo -| barfly 555 ...
Note the second line of output. In the original file (see section Data Files for the Examples), the second line looked like this:
alpo-net 555-3412 2400/1200/300 A
The `-' as part of the system's name was used as the field separator, instead of the `-' in the phone number that was originally intended. This demonstrates why you have to be careful in choosing your field and record separators.
On many Unix systems, each user has a separate entry in the system password file, one line per user. The information in these lines is separated by colons. The first field is the user's logon name, and the second is the user's encrypted password. A password file entry might look like this:
arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
The following program searches the system password file, and prints the entries for users who have no password:
awk -F: '$2 == ""' /etc/passwd
Go to the first, previous, next, last section, table of contents.