HOWTO: Find Files With Specified Text In Them.
Ok, that’s an ugly title, but you get the idea. If you want to search a big ugly text file (like a log, for example) for a certain string, a combination of grep and the pipe symbol can be a life saver.
Grep is worthy of its own entry (heck, books have been written about it), but I’ll touch on it briefly here.
cat myfile | grep xyz
This command will search the file myfile for the string xyz. It will display each line that it finds with xyz in it.
Handy, eh?
Related Stories
POSTED IN: How To
6 opinions for HOWTO: Find Files With Specified Text In Them.
vivek
Feb 1, 2006 at 9:14 am
Use,
grep “text-to-search” file-name
Match word:
grep -Ew “word” file-name
Indeed almost all command can be use this way, no need to use pipe. Have a fun
Jon
Feb 1, 2006 at 9:17 am
Thanks Vivek.
I’m going to do a larger entry (or series) on grep. It’s so powerful and so flexible that it deserves more attention.
pcunix
Feb 2, 2006 at 7:35 am
The tradition in the Unix world is to give you a “useless use of cat award”.
However, it’s not always useless. For example, if I just typed “cat foobar” and now realize I only want the “bar=” lines from that fle, it’s easier (and therefore nore “useful”) for me to press up arrow and add the pipe to “grep” than to retype the whole thing as “cat foobar | grep bar=”
One thing that regularly comes up is how to use grep to search recursively through sub directories. Unfortunately, this question always attracts a lot of incorrect answers because it’s actually not easy to do. See http://aplawrence.com/Unixart/recursivegrep.html for more on that.
Jon
Feb 2, 2006 at 7:40 am
Yay! I win a useless cat award!
:)
I’m sure I do a lot of useless things. One of the saving graces about being a new Linux user writing to other new Linux users is that guys like you who actually know something tend to turn up and help out.
Thanks for the link to recursively searching through subdirectories.
Sean
Feb 13, 2006 at 7:40 am
When grepping multiple files with a glob, grep prepends the name of the file to the output:
grep foo *.txt
1.txt: foo
In scripting, though, you’re often concerned with what’s in the file rather than the name of the file, so cat’ting gets around that:
cat *.txt | grep foo
Yes, there’s an option to remove the name of the file, but why bother when you can cat? :)
Sean
Jon
Feb 13, 2006 at 7:59 am
Thanks Sean!
Have an opinion? Leave a comment: