Grepping ls output

April 14th, 2004

grep is a useful tool for modifying the output from ls (the UNIX directory listing command).

For example, if you want to list only the files beginning with a full stop ("."), you can use the command:

ls -a | grep '^\.'

Note: if you're going to be using \ or * you need to enclose the expression that you pass to grep in single quotes.

I frequently want to list just the directories within the current directory. This is especially useful in a directory with lots of files. To do this I use the command:

ls -l | grep ^d

Which produces something like:

drwxr-sr-x   2 me    mygroup   512 Mar  1  2002 News
drwx--S---   2 me    mygroup   512 Dec  8 12:42 Trash
drwxr-sr-x   3 me    mygroup   512 Jan  9 15:59 cvs
drwxrwsrwx   7 me    mygroup   512 Apr 14 00:28 documents-archive
drwx------   2 me    mygroup   512 Aug  4  2003 downloaded-files
drwx------   2 me    mygroup   512 Sep 18  2002 mail
drwxr-sr-x   3 me    mygroup   512 Feb 11 23:03 perlprogs
drwxrwsrwx   2 me    mygroup   512 Apr 13 23:44 temp
drwx------   2 me    mygroup   512 Aug 28  2003 upload-from-here

If you're only interested in the directory names use:

ls -l | grep ^d | awk '{print $9}'

Which prints only column 9, giving you:

News
Trash
cvs
documents-archive
downloaded-files
mail
perlprogs
temp
upload-from-here



For more information on awk, see:

http://www.linuxfocus.org/English/September1999/article103.html

http://tille.soti.org/training/awk.php

Potentially similar posts

Leave a comment