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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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"'
Method 2
If you are looking to match only part of the string on a given column, you can use advice from https://stackoverflow.com/questions/17001849/awk-partly-string-match-if-column-partly-matches
some_command | awk '$6 ~ /string/'
Method 3
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).
Method 4
I know I’m late to the party, but I believe a very general solution to this problem is to use awk with regular expressions like so:
awk '$3~/rahmu/{print}' input_file
The part enclosed by ‘//’ can be any kind of regular expression.
Method 5
To grep based on single username column (and print only files), you can try:
ls -la | grep "^-S+s+S+s+rahmu"
For directories, change - into d, for any type remove -.
It basically selects each column by S+s+ which matches a non-space characters followed by a space characters, so we’re matching three first columns and then the username.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0