Keeping Only a Portion of a Line of Output

Problem

You want to keep only a portion of a line of output, such as just the first and last words. For example, you would like ls to list just filenames and permissions, without all of the other information provided by ls -l. However, you can’t find any options to ls that would limit the output in that way.

Solution

Pipe ls into awk, and just pull out the fields that you need:

$ ls -l | awk '{print $1, $NF}'
total 151130
-rw-r--r-- add.1
drwxr-xr-x art
drwxr-xr-x bin
-rw-r--r-- BuddyIcon.png
drwxr-xr-x CDs
drwxr-xr-x downloads
drwxr-sr-x eclipse
...
$

Discussion

Consider the output from the ls -l command. One line of it looks like this:

drwxr-xr-x 2 username group      176 2006-10-28 20:09 bin

so it is convenient for awk to parse (by default, whitespace delineates fields in awk). The output from ls -l has the permissions as the first field and the filename as the last field.

We use a bit of a trick to print the filename. Since the various fields are referenced in awk using a dollar sign followed by the field number (e.g., $1, $2, $3), and since awk has a built-in variable called NF that holds the number of fields found on the current line, $NF always refers to the last field. (For example, the ls output line has eight fields, so the variable NF contains 8,so $NF refers to the eighth field of the input line, which in our example is the filename.)

Just remember that you don’t use a $ to read the value of an awk variable (unlike bash variables). NF is a valid variable reference by itself. Adding a $ before it changes its meaning from “the number of fields on the current line” to “the last field on the current line.”

See Also

..................Content has been hidden....................

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