Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
3  
Note that parsing the output of ls is inherently fragile (think what happens if a user name contains whitespace — and yes, this happens on some platforms). Use find instead. –  Gilles Feb 16 '12 at 1:47

2 Answers 2

If by column, you mean fixed-size column, you could:

ls -l | grep "^.\{15\}rahmu"

where ^ means the beginning of the line, . means any character and \{15\} means exactly 15 occurrences of the previous character (any character in this case).

share|improve this answer
up vote 7 down vote accepted

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"' 
share|improve this answer
6  
Or: ls -l | awk '$3=="rahmu"' ... and by the way, the opening ( bracket should be after if ... awk '{if($3 ...' –  Peter.O Feb 15 '12 at 15:11
    
Yes thank you, I corrected that. –  rahmu Feb 15 '12 at 15:34
1  
@Peter.O +1 from me. Your command is more succinct, correct, since print is the default for an awk match. –  bdowning Feb 15 '12 at 16:06
    
To avoid localization issues (date format affects column order) it is often suggested to ensure standard format and language: LANG=C ls -l | awk ... –  fheub Feb 16 '12 at 10:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.