Grep – How to Run Grep on a Single Column

awkgrep

I want to grep the output of my ls -l command:

-rw-r--r--   1 root root       1866 Feb 14 07:47 rahmu.file
-rw-r--r--   1 rahmu user     95653 Feb 14 07:47 foo.file
-rw-r--r--   1 rahmu user   1073822 Feb 14 21:01 bar.file

I want to run grep rahmu on column $3 only, so the output of my grep command should look like this:

-rw-r--r--   1 rahmu user     95653 Feb 14 07:47 foo.file
-rw-r--r--   1 rahmu user   1073822 Feb 14 21:01 bar.file

What's the simplest way to do it? The answer must be portable across many Unices, preferably focusing on Linux and Solaris.

NB: I'm not looking for a way to find all the files belonging to a given user. This example was only given to make my question clearer.

Best Answer

One more time awk saves the day!

Here's a straightforward way to do it, with a relatively simple syntax:

ls -l | awk '{if ($3 == "rahmu") print $0;}'

or even simpler: (Thanks to Peter.O in the comments)

ls -l | awk '$3 == "rahmu"' 
Related Question