防止循环遍历与模式匹配的文件以尝试遍历文字模式?
Prevent loop that iterates over files that match pattern to try to loop over literal pattern?
我有一个循环遍历一系列文本文件(所有格式都是 name.txt
):
for txt in *txt; do
sed -i '$ d' $txt
done
但是每当目录中没有 .txt
文件时,我会收到以下错误消息:
sed: can't read ‘*txt’: No such file or directory
这是因为它没有匹配任何文件并且正在离开 'txt' 而不是执行您期望的操作,即跳过 for 循环。在某些实现中(例如 macOS),它会将字符串保留为 '*txt' 并且 运行 将变量 txt 设置为 *txt 的 for 循环。在尝试 运行 for 循环之前,您需要先测试文件模式是否存在。参见 Check if a file exists with wildcard in shell script。
您可以通过两种方式解决此问题:
a) 在对文件进行任何操作之前检查文件是否存在
for txt in *txt; do
[[ -f "$txt" ]] || continue # skip if file doesn't exist or if it isn't a regular file
# your logic here
done
b) 使用 shell 选项 shopt -s nullglob
这将确保在没有匹配文件时 glob 扩展为空
shopt -s nullglob
for txt in *txt; do
# your logic here
done
另请参阅:
我有一个循环遍历一系列文本文件(所有格式都是 name.txt
):
for txt in *txt; do
sed -i '$ d' $txt
done
但是每当目录中没有 .txt
文件时,我会收到以下错误消息:
sed: can't read ‘*txt’: No such file or directory
这是因为它没有匹配任何文件并且正在离开 'txt' 而不是执行您期望的操作,即跳过 for 循环。在某些实现中(例如 macOS),它会将字符串保留为 '*txt' 并且 运行 将变量 txt 设置为 *txt 的 for 循环。在尝试 运行 for 循环之前,您需要先测试文件模式是否存在。参见 Check if a file exists with wildcard in shell script。
您可以通过两种方式解决此问题:
a) 在对文件进行任何操作之前检查文件是否存在
for txt in *txt; do
[[ -f "$txt" ]] || continue # skip if file doesn't exist or if it isn't a regular file
# your logic here
done
b) 使用 shell 选项 shopt -s nullglob
这将确保在没有匹配文件时 glob 扩展为空
shopt -s nullglob
for txt in *txt; do
# your logic here
done
另请参阅: