I am using Ubuntu machine and tried with below commands to search for a text:
This command to check if the word is present in a given directory recursively:
1) Here <hello>
is the word which I am search for and it searches recursively in all files starting from current directory. It is working fine.
grep -r "<hello>" .
2) Now I want to restrict the search to only specific files, say to xml
files only:
grep --include=\*.{java} -rnw '/home/myfolder/' -e "<hello>"
This time the command is taking more time and finally not giving any results. But my files has the content.
I have gone through this link - How do I find all files containing specific text on Linux? for writing my second command.
Is there any issue with my second command? Also is there an alternate command that performs fast?
It might be better to use
find
, sincegrep
's include/exclude can get a bit confusing:This looks for files whose name finishes with
.xml
and performs agrep 'hello'
on them. With-l
(L) we make the file name to be printed, without the matched line.Explanation
find -type f
this finds files in the given directory structure.-name "*.xml"
selects those files whose name finishes with.xml
.-exec
execute a command on every result of thefind
command.-exec grep -l 'hello' {} +
executegrep -l 'hello'
on the given file. With{} +
we are refering to the matched name (it is like doinggrep 'hello' file
but refering to the name of the file provided by thefind
command). Also,grep -l
(L) returns the file name, not the match itself.