Finding Text with grep


Finding Text with grep

You can search through multiple files for specific strings of characters and then view the list of matching files onscreen. You do this using the grep command (which stands for "global regular expression print," a once useful and now rather arcane ed or vi command), as shown in Code Listing 6.7. As we'll show you, you can add several flags to grep to get slightly different results.

Code Listing 6.7. Use grep to see all occurrences of a specific string in a file.

[ejr@hobbes manipulate]$ grep bucket  limericks Who carried his lunch in a bucket, [ejr@hobbes manipulate]$ 

Code Listing 6.8. grep can show the context around instances of the string as well.\

[ejr@hobbes manipulate]$ grep -5 bucket  limerick he strummed and he hummed, and sang dumdeedum, But him a musician...whoda thunk it? There once was a man from Nantucket, Who carried his lunch in a bucket, Said he with a sigh, As he ate a whole pie, If I just had a donut I'd dunk it. A nice young lady named Debbie, [ejr@hobbes manipulate]$ 

To find text strings with grep:

  • grep bucket limericks

    At the shell prompt, type grep, the text you're trying to locate (in this case, bucket), and the file you're searching in (here, limericks). grep will return all lines in the file that contain the specified string, as shown in Code Listing 6.7.

  • grep -5 bucket limericks

    You can specify that a number of lines (say 5) on either side of the found text string should also be displayed. Sometimes you can't tell what you need to know with just the line that contains your search string, and adding lines around it can help give you a context (see Code Listing 6.8). Note that this option isn't available on all versions of grep, but it'll work for most.

  • grep -c Nantucket limericks

    By adding the -c flag, you can find out how many times a text string appears in a file.

  • grep -v Nantucket limericks

    Or, with the -v flag, you can find all of the lines that do not contain the specified string.

  • grep -i nantucket limericks

    With the -i flag, you can search without case-sensitivity. Here any line with nantucket or Nantucket or nAntuCKet would be found.

Tips

  • Use the -n flag (for example, grep -n string file) to print each found line with a line number.

  • You can use grep with multiple filenames, such as in grep Nantucket lim* or grep Nantucket lim* poetry humor.

  • If you want to get creative, you can look for spaces as well, but you need to use quotes, like grep "from Nantucket" limerick*.

  • Win nerdy bar bets by knowing the heritage of grep.





Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

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