【问题标题】:Command line for loop with a nested if statement带有嵌套 if 语句的循环命令行
【发布时间】:2021-07-04 12:43:56
【问题描述】:

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

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

我的思路是

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

【问题讨论】:

    标签: shell terminal grep


    【解决方案1】:
    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 并且很高兴它将删除您期望的文件。

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 如果当前目录可以包含子目录,那么你可以在grep之前的循环中添加[[ -d "$file" ]] && continue语句或使用grep -d skip ...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多