With either OSX or *nix OS, console outputs have text data in columns. Sometimes it may required to parse column based console output to get specific row or column value. In this article we will use a combination of sort, head, tail, tr, cut commands to get particular row or column value from console output.
Lets start with ls command which returns the folder and files name as shown below:
$ ls -l
total 8
drwxr-xr-x 2 avkash staff 68 Sep 17 00:10 Any
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Apps
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Books
drwxr-xr-x 2 avkash staff 68 Sep 17 00:08 Code
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Music
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Songs
drwxr-xr-x 2 avkash staff 68 Sep 17 00:08 Zeppos
-rw-r–r– 1 avkash staff 46 Sep 17 00:23 data.txt
$ ls -l | head -n 2 | tr -s ‘ ‘ | cut -d’ ‘ -f9
Any
$ ls -l | tail -n 1 | tr -s ‘ ‘ | cut -d’ ‘ -f9
data.txt
You can also use this trick with sorting command output using sort command (-n, -M, -d etc….)
$ ls -l | sort -n
-rw-r–r– 1 avkash staff 46 Sep 17 00:23 data.txt
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Apps
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Books
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Music
drwxr-xr-x 2 avkash staff 68 Sep 17 00:07 Songs
drwxr-xr-x 2 avkash staff 68 Sep 17 00:08 Code
drwxr-xr-x 2 avkash staff 68 Sep 17 00:08 Zeppos
drwxr-xr-x 2 avkash staff 68 Sep 17 00:10 Any
total 8
$ ls -l | sort -n | tail -n 2 | tr -s ‘ ‘ | cut -d’ ‘ -f9
Any
$ ls -l | sort -n | head -n 1 | tr -s ‘ ‘ | cut -d’ ‘ -f9
data.txt
This trick does works with any text in console i.e. you could use output of a file as well.
Example 2:
$ cat data.txt
Any
Apps
Books
Code
Gum
Music
Songs
Zeppos
X
$ cat data.txt | tail -n 1 | tr -s ‘ ‘ | cut -d’ ‘ -f1
X
$ cat data.txt | head -n 1 | tr -s ‘ ‘ | cut -d’ ‘ -f1
Any
Thats all. Have fun!!
Thanks to my friend Aaron for showing this great trick.
Keywords: ls, sort, head, tail, tr, cut