简体   繁体   English

如果grep失败,请删除该文件

[英]If grep fails delete the file

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 :) Heya伙计们,我有这个小脚本,我需要grep所有的文件,只留下包含关键字的文件,我坚持这一点,任何帮助指出我的愚蠢的错误是赞赏:)

#!/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

.
.
.

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. 使用grep选项-q来清除输出和-s以禁止显示错误消息。

you can use -l option for grep 你可以使用-l选项为grep

grep -l "KEYWORD" directory/server*html | while read -r FOUND
do
   rm -f .....
   do some other processing here.....
done

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). 有效索引从023 (比数组元素的数量少一个)。
    So your for loop should be: 所以你的for循环应该是:

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

I would suggest you do the grep for each file and then test the exit status $? 我建议你为每个文件做grep,然后测试退出状态$? - 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
#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM