Operating System - HP-UX
1755772 Members
2503 Online
108838 Solutions
New Discussion юеВ

Re: Search specific string in a file in a sub-folder

 
SOLVED
Go to solution
Nameesh
Frequent Advisor

Search specific string in a file in a sub-folder

Hi,

What is the command to be used to search for occurance of specific string in a file present at a sub-directory from the root.

Regards,
Nameesh.
7 REPLIES 7
Steve Steel
Honored Contributor

Re: Search specific string in a file in a sub-folder

Hi


try

find . -name file|xargs grep -il "string"


Steve Steel
If you want truly to understand something, try to change it. (Kurt Lewin)
Pete Randall
Outstanding Contributor

Re: Search specific string in a file in a sub-folder

Or, simply:

grep -l "string" /sub-directory/*


Pete

Pete
Robert-Jan Goossens
Honored Contributor
Solution

Re: Search specific string in a file in a sub-folder

I would add the -type f to the find command just in case you hit binary files.

# find . -type f | xargs .......

Robert-Jan
Jakes Louw
Trusted Contributor

Re: Search specific string in a file in a sub-folder

Robert-Jan is right. Pete's "grep string /path/* " will work, but will go thru binary files. (although I also do this, being a lazy sod.....;-> )
Trying is the first step to failure - Homer Simpson
Marton Ferenc
Advisor

Re: Search specific string in a file in a sub-folder

from man grep

Search all files in the current directory for the string xyz:

grep xyz *

Search all files in the current directory subtree for the string xyz,
and ensure that no error occurs due to file name expansion exceeding
system argument list limits:

find . -type f -print |xargs grep xyz

The previous example does not print the name of files where string xyz
appears. To force grep to print file names, add a second argument to
the grep command portion of the command line:

find . -type f -print |xargs grep xyz /dev/null

In this form, the first file name is that produced by find, and the
second file name is the null file.
J5000
Elmar P. Kolkman
Honored Contributor

Re: Search specific string in a file in a sub-folder

I don't like to disagree with some guys, but... the '-type f' for find does not look into a file, it only looks at the kind of inode: the result will be it will only look at normal files and skip directories, symbolic links, pipes, devices, etc. But binary files, like executables, will be searched.

Also, what I miss is the single command solution:
find . -type f -exec grep -il {} \;

It might be less effecient as the xargs...
If you only want ASCII files, you can then filter the output using the file command on every file reported by the find command.
Every problem has at least one solution. Only some solutions are harder to find.
Marton Ferenc
Advisor

Re: Search specific string in a file in a sub-folder

Elmer message:

Is the quetion related occurence of string in files or in a filename?

in first case:
Do you want to get number of occurence or a filelist?

J5000