首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有嵌套if语句的for循环命令行

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

Stack Overflow用户
提问于 2021-07-04 20:43:56
回答 2查看 53关注 0票数 0

我需要遍历同一目录中的所有文件,如果在该目录中的任何文件中存在特定行"File need be delete“,则只删除这些文件。从命令行它是如何工作的呢?

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

我是沿着这样的路线走的

代码语言:javascript
运行
复制
for each file the directory; do
  if [ row text == "File needs to be deleted" ]; then
    delete file
  fi
done
EN

回答 2

Stack Overflow用户

发布于 2021-07-04 20:57:02

简单的bash示例:

代码语言:javascript
运行
复制
#!/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
票数 2
EN

Stack Overflow用户

发布于 2021-07-04 21:41:03

代码语言:javascript
运行
复制
grep -d skip -lF 'File needs to be deleted' file* | xargs echo rm --

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

代码语言:javascript
运行
复制
find . -maxdepth 1 -type f -exec grep -lF 'File needs to be deleted' {} + | xargs echo rm --

一旦你测试了echo,并且很高兴它能删除你期望的文件,就删除它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68244840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档