views:

85

answers:

5

Heya guys, I have this small script and i need to grep all the files and leave only the ones that contain a keyword and I'm stuck on this, any help in pointing out my dumb errors is appreciated :)

#!/bin/bash

server=(server1...server24)

.
.
.

for ((n=0; n <= 24 ; n++))
do
        if grep -q "KEYWORD" directory/${server[$n]}.html ; then
                echo Empty
        else
                rm -f directory/${server[$n]}.html
        fi
done

.
.
.
+1  A: 

you can use -l option for grep

grep -l "KEYWORD" directory/server*html | while read -r FOUND
do
   rm -f .....
   do some other processing here.....
done
ghostdog74
grep -l "KEYWORD" directory/*.html | xargs -r rm -f
pixelbeat
-L not -l for files _without_ match
pixelbeat
Dang :) This is the best answer, as long as you incorporate both of @pixelbeat's comments. And, according to OP's requirements, change `directory/server*html` into `$server`.
Amadan
sure, `xargs` can be used. But i am not going to change my answer. Since I am assuming some other processing need to be done as well.
ghostdog74
+1  A: 

Ensure the following:

  • Separate the server names in the array by whitespace as:

    server=(server1 server2 server3 ... server24)

  • The valid indices are from 0 to 23 (one less than the number of array elements).
    So your for loop should be:

    for ((n=0; n <= 23 ; n++)) or for ((n=0; n < 24 ; n++))

codaddict
actually i do need the line because each of my servers has a different hostname, i just put in server1-24 for simplifying the code here.
f10bit
A: 

I would suggest you do the grep for each file and then test the exit status $? - and fix your brace expansion.

so...

 for ((n=0; n <= 24 ; n++))
    do
      grep -q "KEYWORD" directory/server${n}.html
      if [ $? -eq 0 ] then
          echo "directory/server${n}.html - Has keyword"
      else
          rm -f directory/server${n}.html
      fi
    done
slomojo
That's exactly what `if grep ... ; then` is already doing.
Nefrubyr
That's why it's just a suggestion (it aids readability) .. The brace expansion fixes the error.
slomojo
A: 
#!/usr/bin/env bash

server=(server{1..24})

for((n=0; n<24; n++))
do
    if grep -q 'keyword' ${server[$n]}; then
        echo Empty
    else
        rm -f ${server[$n]}
    fi
done
Casual Coder
+2  A: 

You don't have to make sure your count matches if you let your code do it for you in one of the following ways:

servers=(foo bar baz)
for server in ${servers[@]}
do
    if ! grep -qs "KEYWORD" directory/$server.html 
    then
        rm ...

or

servers=(foo bar baz)
for ((n = 0; n < ${#servers[@]}; n++))
do
    if ! grep -qs "KEYWORD" directory/${servers[$n]}.html 
    then
        rm ...

Use ! to invert the condition so that it's "if the file does NOT contain the keyword, then delete it".

Use the grep option -q to quiet the output and -s to suppress error messages.

Dennis Williamson