Grep based on column

Grep based on column

So ever found the need to run a grep based on column value instead of the entire output?

So take an example of the following output:

[[email protected] ~]# ls -lah
.
.
-rw-------  1 root  root  442M Feb 17  2012 project_inprogress.pdf
-rw-------  1 gagan gagan 4.3K Mar  4  2012 jmeter.log
-rw-------  1 gagan gagan 5.4K Jul 19  2012 June-2012.pdf
-rw-------  1 root  root  5.4K Jul 19  2012 June-2012-gagan.pdf
-rw-------  1 gagan gagan 5.4K Jul 19  2012 May-2012.pdf
.
.

So in the above output, I need to find the files which are owned by the user gagan. So if use grep gagan, it will then give the output something like below:

[[email protected] ~]# ls -lah
.
.
-rw-------  1 gagan gagan 4.3K Mar  4  2012 jmeter.log
-rw-------  1 gagan gagan 5.4K Jul 19  2012 June-2012.pdf
-rw-------  1 root  root  5.4K Jul 19  2012 June-2012-gagan.pdf
-rw-------  1 gagan gagan 5.4K Jul 19  2012 May-2012.pdf
.
.

See the additional file which is actually owned by root and not gagan.

Grep based on column

So in the above case we need to find the files which are user owned by gagan, which can be found in column 3.

So instead of grep we will use awk.

The following is the syntax that can be used:

awk ‘$NUM == “STRING”‘

or

awk ‘{if ($NUM == “STRING”) print $0;}’

In my opinion, the first syntax is simpler.

So in our example above, we will use something like the following:

[[email protected] ~]# ls -lah | awk ‘$3 == “gagan”‘

Output:

-rw-------  1 gagan gagan 4.3K Mar  4  2012 jmeter.log
-rw-------  1 gagan gagan 5.4K Jul 19  2012 June-2012.pdf
-rw-------  1 gagan gagan 5.4K Jul 19  2012 May-2012.pdf

That should do it. This can also be usedful while trying check certain results in the netstats output.

Grep based on column

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.