Tuesday 24 April 2012

grep'n'dash

So you somehow have gotten in to the position that you have a file called '-f' containing various strings and one of those strings managed to be '-lookatme!' which is exactly what you need to find. The subtleties of combining the UNIX shell and commands sometimes both confuse and surprise users with unexpected output. Finding these neat tricks will help you understand the intricacies of your *NIX system.

So here is our absurdly named file:

> ls -la
total 32
-rw-r--r--   1 will sysadmin      80 Apr 18 11:08 -f
drwxr-xr-x   3 will sysadmin    4096 Apr 18 11:08 .
drwxr-xr-x   3 will sysadmin    4096 Apr 18 09:50 ..


And look at what's inside:

> cat ./-f
string1
string2
string3
string4
string1
string2
-lookatme!
string3
string4
-end


In this very basic example we want to find the string '-lookatme!'. Using grep we must escape the '-' character in the string we are looking for:

>grep "\-lookatme!" ./-f
-lookatme!


Or we can wrap the filename around double-quotes:

>grep "\-lookatme!" "-f"
-lookatme!


You can even search an entire directory for that ridiculous string:

>grep "\-lookatme!" *
-f:-lookatme!

No comments:

Post a Comment