Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

grep under subfolders

Status
Not open for further replies.

unixwhoopie

Programmer
May 6, 2003
45
US
If I have main folder called /var/opt/dshs
and there are several subfolders like A1, A2, A3,....

The complete dir structure is
/var/opt/dshs/A1/input/myfile.txt

This myfile.txt is under each folder, A1, A2,...

I want to grep a specific word from each of these files myfile.txt.

Do I have to write a unix script to loop through all the folders? or is there a direct grep command that I can execute under /var/opt/dshs.

Thanks
 
You can feed grep with a find command if the filenames are consistent:
$ cd /var/opt/dshs
$ find . -type f -name myfile.txt -exec grep YOURWORD {} \;

Or, if the pathnames and filenames are consistent, you can include those in your grep command:
$ cd /var/opt/dshs
$ grep YOURWORD ./A*/input/myfile.txt

 
And what about man grep ?
If the man page talks about -r or -R or -d recurse, then you're lucky !
Otherwise, you may try this:
grep your grep options here /var/opt/dshs/A*/input/myfile.txt
Or this:
find /var/opt/dshs -name myfile.txt | xargs grep your grep options here

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
find is probably the way to go. "grep -r" seems like it would work, but I've had *no* luck using it on specific filenames.
 
You can use this to apply a command to all files in all subdirectories

-------------------------------------------------
PN=`basename "$0"`

Usage () {
echo >&2 "$PN - apply command to all files in all subdirectories
usage: $PN command [arg ...]

The given command will be applied to all files in the current
and in all subdirectories -- USE WITH CARE."
exit 1
}

[ $# -lt 1 ] && Usage

find * -type f -print | xargs "$@"

-----------------------------------------------

So you'd do

cd /var/opt/dshs
$PN command [args]

e.g
$PN cat myfile.txt|grep aword

Mike

"A foolproof method for sculpting an elephant: first, get a huge block of marble, then you chip away everything that doesn't look like an elephant."

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top