遍历文件中的文件位置以检查它们是否存在



我在bash中编写这个命令来检查系统中的文件。文件位置写入"New.txt":

for files in $(grep "spider" "New.txt"); do if test -e "$files"; then echo $files; else echo "NOT $files"; fi; done
Output: 
NOT C:/USERS/IBRAHIM/my_spider.csv
NOT C:/USERS/IBRAHIM/spider.txt
C:/USERS/IBRAHIM/newspider.txt

由于某种原因,它只接受文件中最后出现的内容,尽管"spider.txt"也是发现的。如果我尝试切换New.txt中的最后两行,它将只接受最后出现的内容,在这种情况下是"spider.txt"。有人能帮帮我吗?由于

如果任何路径都包含空格,则此方式使用grep将不起作用。

我建议使用Bash内置readarray来加载您的"New.txt"到一个数组中,并遍历它

readarray -t my_list < <(grep -q 'spider' "New.txt")
for file in "${my_list[@]}"; do 
if [ -e "$file" ]; then
echo "$file"
else
echo "NOT $file"
fi
done

使用grep的另一种选择是使用Bash正则表达式:

readarray -t my_list < "New.txt"
for file in "${my_list[@]}"; do 
[[ "$file" =~ spider ]] || continue
if [ -e "$file" ]; then
echo "$file"
else
echo "NOT $file"
fi
done

据我所知,你的要求是。

你想循环抛出一个文件中存在的文件列表,并检查每个文件是否存在。

下面是一个例子,spider.sh:

#!/bin/bash
function usage(){
echo "./program file pattern"
}
function process(){
[ ! -f $1 ] && echo "Main file("$1") not found !" && exit 1
# Get all lines with the pattern $2 and check if it is actually a file
for file in $(grep $2 $1); do
[ -f $file ] && echo "$file" || echo "NOT $file"
done
}
[ $# -ne 2 ] && usage || process $1 $2;

简单用法:

创建2个存在的蜘蛛文件,1个不存在的蜘蛛文件,1个存在的非蜘蛛文件和一个不存在的非蜘蛛文件

$ touch spiderfiles.txt spider_file{1,2}.txt other_file.txt
$ echo $(realpath spider_file1.txt) >> spiderfiles.txt
$ echo $(realpath spider_file2.txt) >> spiderfiles.txt
$ echo $(realpath other_file.txt) >> spiderfiles.txt
$ echo "/non/existing/spider_file.txt" >> spiderfiles.txt
$ echo "/non/existing/file.txt" >> spiderfiles.txt

如何使用脚本:

第一个参数:包含文件路径的文件

第二个参数:查找

的模式
./spider.sh spiderfiles.txt spider

结果如预期:

/home/talel/Documents/Stackoverflow/files/spider_file1.txt
/home/talel/Documents/Stackoverflow/files/spider_file2.txt
NOT /non/existing/spider_file.txt

最新更新