Search the Output of Other Commands for Specific Words


$ ls -1 | grep 1960

The grep command is powerful when used by itself, but it really comes alive when you use it as a filter for the output of other programs. For instance, let's say you have all your John Coltrane MP3s organized in separate subfolders for each album (66 in all ... yes, Coltrane is that good), with the year at the beginning. A partial listing might look like this (the -1 option is used with ls so there is one result on each line):

$ ls -1 1956_Coltrane_For_Lovers 1957_Blue_Train 1957_Coltrane_[Prestige] 1957_Lush_Life 1957_Thelonious_Monk_With_John_Coltrane 


Now, what if you just wanted to see a list of the albums you own that Coltrane released in 1960? Pipe the results of ls -1 to grep, and you'll get your answer in seconds.

$ ls -1 | grep 1960 1960_Coltrane_Plays_The_Blues 1960_Coltrane's_Sound 1960_Giant_Steps 1960_My_Favorite_Things 


After you start thinking about it, you'll find literally hundreds of uses for grep in this way. Here's another powerful one. The ps command lists running processes, while the -f option tells ps to give the full listing, with lots of information about each process, and the -U option, followed by a username, restricts the output to processes owned by that user. Normally ps -fU scott would result in a long list, too long if you're looking for information about a specific process. With grep, however, you can easily restrict the output.

Note

To save space, some of the information you'd normally see with ps has been removed.


$ ps -fU scott | grep firefox scott 17623 /bin/sh /opt/firefox/firefox scott 17634 /opt/firefox/firefox-bin scott 1601 grep firefox 


The ps command lists all commands owned by the scott user (64, in fact), but pipes that output to grep, which lists only those lines that contain the word firefox in them. Unfortunately, the last line of output is erroneous: You only care about the actual Firefox program, not the search for firefox using grep. To hide the search for firefox in the grep results, try this instead:

$ ps -fU scott | grep [f]irefox scott 17623 /bin/sh /opt/firefox/firefox scott 17634 /opt/firefox/firefox-bin 


Now your grep search term used a regex range, from f to f, that found firefox on those lines output by ps in which Firefox was running; however, it didn't match the line for grep because that line was actually [f]irefox, which wouldn't match. The grep command here can't match the original string ps -ef | grep [f]irefox because it contained [ and ], and the grep search for [f]irefox resolves to searching for the exact word firefox. This is a bit confusing, but if you try it yourself and think about it a bit, it'll make some sense. At any rate, it works. Give it a try!



Linux Phrasebook
Linux Phrasebook
ISBN: 0672328380
EAN: 2147483647
Year: 2007
Pages: 288

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net