带有嵌套 if 语句的命令行 for 循环

时间:2021-07-04 12:43:56

标签: shell terminal grep

我需要遍历同一目录中的所有文件,并且如果该目录中的任何文件中存在特定行“文件需要删除”,则仅删除这些文件。请问它如何从命令行工作?

例如,该目录包含 file1、file2、file3 等 1000 个文件。每个文件有 10,000 行字符串。如果任何文件包含字符串“文件需要删除”,则删除这些文件,但不要删除不包含该字符串的文件。

我一直在走

for each file the directory; do
  if [ row text == "File needs to be deleted" ]; then
    delete file
  fi
done

2 个答案:

答案 0 :(得分:2)

简单的 bash 示例:

#!/bin/bash
# Get the running script name
running_script=$(realpath $0 | awk -F '/' '{ print $NF }')
# Loop throw all files in the current directory
for file in *; do
    # If the filename is the same as the running script pass it.
    [ "$file" == "$running_script" ] && continue
    # If "File needs to be deleted" exists in the file delete the file.
    grep -q "File needs to be deleted" "$file" && rm "$file"
done

答案 1 :(得分:2)

grep -d skip -lF 'File needs to be deleted' file* | xargs echo rm --

如果您的当前目录中只有文件,没有目录,那么您只需删除 -d skip。如果您的 grep 版本没有 -d 但您的目录确实包含子目录,则:

find . -maxdepth 1 -type f -exec grep -lF 'File needs to be deleted' {} + | xargs echo rm --

测试后删除 echo 并且很高兴它会删除您期望的文件。