March 4, 2013 by James

Get the last column from the output of ls -l

so, with a file/output like this:

drwxrwxr-x    35 user1       www            1536 May 13  2010 dir1
drwxrwxr-x    19 user2       www             512 Sep 28 11:36 dir2
drwxrwxr-x     5 user3       www            1024 Jan 11  2010 dir3
drwxrwxr-x     5 user4       www          398848 Oct  5  2010 dir4
drwxrwxr-x    10 user5       www             512 Feb 23  2012 dir5

sometimes I want to extract the last field.  You can dick about with cut(5) etc –  but that is  quite tedious.

Whilst idly reading the bash man page in the bath, I stumbled across this builtin:

Remove matching prefix pattern.  The word is expanded to produce
a pattern just as in pathname expansion.  If the pattern matches
the  beginning of the value of parameter, then the result of the
expansion is the expanded value of parameter with  the  shortest
matching  pattern  (the “#'' case) or the longest matching pat-
tern (the “##'' case) deleted.  If parameter is  @  or  *,  the
pattern  removal operation is applied to each positional parame-
ter in turn, and the expansion is the resultant list.  If param-
eter  is  an array variable subscripted with @ or *, the pattern
removal operation is applied to each  member  of  the  array  in
turn, and the expansion is the resultant list.

wat ? we need a real world example:

cat /tmp/dirs | while read line ; do echo ${line##*\ } ; done


Thats pretty handy !