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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting Files based on content value

Status
Not open for further replies.

tbohon

Programmer
Apr 20, 2000
293
0
0
US
I have a directory with perhaps 1000 files and I need to copy only those containing the value Med Admin Rpt to a different directory. Have tried several things and they aren't working - and, of course, the boss is asking me for my progress every 15 minutes.

Help??? :)

Tnx.

Tom

"My mind is like a steel whatchamacallit ...
 
Code:
#!/bin/ksh
for file in *
do
   [ grep -q 'Med Admin Rpt' "${file}" 2>/dev/null ] && cp "${file}" /path/to/different/directory
done

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Doesn't seem to work. Script executes just fine but nothing is copied. I've double-checked the Med Admin Rpt and that is exactly the phrase they want selected ... ???

"My mind is like a steel whatchamacallit ...
 
To make the script easier to debug try
Code:
#!ksh 
fof file in *
do
  echo testing $file
  if grep -q 'Med Admin Rpt' $file
  then
    echo 'Med Admin Rpt' found in $file
    cp $file /path/to/different/directory
  fi
done
When you've got it workign you can comment out the echoes.

Ceci n'est pas une signature
Columb Healy
 
Thanks. I'll give it a shot.

"My mind is like a steel whatchamacallit ...
 
Alternative, for a more diverse/general purpose search..

Code:
function find_and_copy() {
STRING=${1:?"Please specify a search string."}
DIRECTORY=${2:-$PWD}
DESTINATION=${3:-/tmp/found}


[ ! -d "$DESTINATION" ] && mkdir $DESTINATION

for a in `find $DIRECTORY -type f -exec grep -l $STRING {} \;`
do
    cp -p $a $DESTINATION 2>/dev/null || echo "Could not copy matching file $a to $DESTINATION"
done
}

HTH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top