我需要遍历同一目录中的所有文件,如果在该目录中的任何文件中存在特定行"File need be delete“,则只删除这些文件。从命令行它是如何工作的呢?
例如,该目录包含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发布于 2021-07-04 20:57:02
简单的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发布于 2021-07-04 21:41:03
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,并且很高兴它能删除你期望的文件,就删除它。
https://stackoverflow.com/questions/68244840
复制相似问题