How Do I Search By Keyword To See Which File It's Located In?
If I wanted to search for a keyword inside of a file, would I be able to do this via Linux? I am running Ubuntu 18.04.
I know of the grep command but I am not sure how I can have it pull the file name of the keyword I am searching for.
For example, I know my server’s IP address is stored in etc/hosts file. But let’s just say I can’t remember the name of this file. Would I be able to search by server IP address (i.e. the keyword that’s contained in the file host) in Linux command line so that my end output shows the name of the file = hosts?
Thank you so much for the help! :)
2 Replies
You should have a look at find(1). Using your example,
find /etc -exec grep -l '1.2.3.4' {} \;
Would list all the files in /etc
containing the regex 1.2.3.4
.
You’ll have to be careful about quoting the regex properly and form the syntax of the -exec
option correctly.
If you wanted to restrict your search to all the files in /etc
matching a filename regex, use the -name <fileregex>
option too:
find /etc -name '*foo*' -exec grep -l '1.2.3.4' {} \;
You can do quite sophisticated searches by forming predicates of search criteria. Do a man find
to see more…
find(1) first appeared in ATT Unix System V -- Programmer's Workbench (in 1983) so it’s been around quite awhile. The GNU version is part of every distro of Linux I've ever seen & improves upon the original quite a bit. I'm pretty sure it's present when you boot your Linode into Rescue Mode too.
find(1) is also available in Terminal windows on every version of macOS too…albeit the BSD version so there are slight differences from the GNU version.
See also:
https://www.tecmint.com/35-practical-examples-of-linux-find-command/
— sw
Wow. I am impressed Steve. Thank you for the productive reply. This was extremely helpful.