I want to search for a string "my-search-string" in any files called search-this-one.html
In all subdirectories of my current working directory.
I want a list of full paths of the files that contain this string. There are hundreds of files called search-this-one.html, any number of them could contain the string.
Has anyone had any success doing this.
I can get a list of files like this..
find . -type f -name "search-this-one.html"
I've tried a variety of grep and ack switches on this, all the other related answers search only for filenames that match the search string.
You could use xargs
:
find . -type f -name "search-this-one.html" | xargs grep "my-search-string"
With the additional -l
switch to grep
, you would get a list of matching files without the exact matching position.
If you're running ack 2.x, you can use the -x option to get input from STDIN, much like xargs.
ack -g search-this-one.html | ack -x pattern
The ack -g
says "Find any text files with names that match search-this-one.html
", and then that's piped into ack -x
which takes its list of input files from STDIN.
Also works for searching for filenames with regex:
ack -g '\.*.conf$' | ack -x searchString
Add an -exec
in your find
command:
find . -type f -name "search-this-one.html" -exec grep "my-search-string" {} \;
So that find
will output a list of file names on which the command grep "my_search_string"
will be performed.
To get the files and the occurrences in which this happens, add -H
to the grep
:
find . -type f -name "search-this-one.html" -exec grep -H "my-search-string" {} \;
For whatever it's worth, I've never found a succinct way to do this using ack
, but the following works:
ack --type-add foo:is:search-this-one.html --foo my-search-string
Explanation:
--type-add foo:is:search-this-one.html
: this adds (for the duration of this one command) a new type, foo
, defined as all files whose name is
search-this-one.html
--foo
: search only files of the type foo
Also, further to @fedorqui et al, you can instead use the -exec cmd {} +
option to find, which puts all the matched filenames into the command before running it, eschewing the need for the -H
flag:
find . -name search-this-one.html -type f -exec grep "my-search-string" {} +
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.