【发布时间】:2021-09-06 03:35:56
【问题描述】:
目前我正在编写一个脚本,我需要在不知道文件扩展名的情况下检查目录中是否存在某个文件。我试过这个:
if [[ -f "$2"* ]]
但这没有用。有谁知道我该怎么做?
【问题讨论】:
-
您有哪些关于此文件的信息?
-
@MonsieurMerso 该文件是受密码保护的 zip 文件。因此我们不知道扩展名。
标签: bash
目前我正在编写一个脚本,我需要在不知道文件扩展名的情况下检查目录中是否存在某个文件。我试过这个:
if [[ -f "$2"* ]]
但这没有用。有谁知道我该怎么做?
【问题讨论】:
标签: bash
-f 需要一个参数,而 AFIK,在这种情况下你不会得到文件名扩展。
虽然很麻烦,但我能想到的最好的方法是生成一个包含所有匹配文件名的数组,即
shopt -s nullglob
files=( "$2".* )
并测试数组的大小。如果它大于 1,则您有多个候选者。即
if (( ${#files[*]} > 1 ))
then
....
fi
如果大小为 1,${files[0]} 会为您提供所需的大小。如果大小为 0(仅当您打开 nullglob 时才会发生这种情况),则没有匹配的文件。
如果您不再需要它,请不要忘记重置 nullglob。
【讨论】:
在 shell 中,您必须迭代每个文件 globbing 模式的匹配并单独测试每一个。
以下是使用标准 POSIX shell 语法的方法:
#!/usr/bin/env sh
# Boolean flag to check if a file match was found
found_flag=0
# Iterate all matches
for match in "$2."*; do
# In shell, when no match is found, the pattern itself is returned.
# To exclude the pattern, check a file of this name actually exists
# and is an actual file
if [ -f "$match" ]; then
found_flag=1
printf 'Found file: %s\n' "$match"
fi
done
if [ $found_flag -eq 0 ]; then
printf 'No file matching: %s.*\n' "$2" >&2
exit 1
fi
【讨论】:
你可以使用find:
find ./ -name "<filename>.*" -exec <do_something> {} \;
<filename> 是不带扩展名的文件名,do_something 是您要启动的命令,{} 是文件名的占位符。
【讨论】: