Unix / Linux: Grep on One Column

Objective: Perform grep on one single column and if there’s a match, print the whole line.

Performing a grep on a multi-column input can be performed by either the grep or the awk utilities. Before we look at an example, let’s look at two different sample inputs – an output of ‘ls -l‘ and the contents of the /etc/passwd file. First, let’s look at the output of ‘ls -l‘.

Now, to grep for lines where the file owner is root, we will need to do a regex match on column 3. Below is an example to do that using grep with extended regex support.

With awk, it is going to be something like this – we do a regex match on field 3 and if it’s a match, we print the whole line. An example is shown below.

Let’s now look at the /etc/passwd file. Below is a truncated output.

To list all lines that have ‘/bin/false‘ as the shell using grep, we will need to do something like this.

With awk, it’s a bit more straight forward – we define the field separator and perform a regex match on the 7th field.

Personally, I prefer to use awk to do pattern matching on a single column – the regular expression is only for the field that we are interested in. With grep, the regular expression is normally for the whole line and not just for the column that we are interested in – so it tends to get a lot more complicated.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }