检查文件是否仅由文件名存在(没有扩展名)

时间:2012-11-06 08:22:46

标签: linux bash shell

这很好用

if [[ -e img.png ]]
then
     echo "exist"
else
     echo "doesn't exist"
fi

但是如果我知道可能存在名称img但我不知道该文件是.jpg,.gif,.jpeg,.tff等等。

如果有一个名为'img'的文件

,我不在乎我想知道的扩展名是什么

我该怎么做?

5 个答案:

答案 0 :(得分:2)

您可以使用以下脚本

files=`ls img.* 2>/dev/null`
if [ "$files" -a ${#files[@]} ]; then
    echo "exist"
else
    echo "doesn't exist"
fi

在此代码段中,您使用ls img.*列出当前工作目录中名称与模式img.*匹配的所有文件。 结果存储在名为files的数组中。 然后检查数组的大小以确定是否存在所需文件。

请参阅this了解如何获取数组的长度。

答案 1 :(得分:2)

你可以这样做:

files=$(ls img.* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "exist"
else
echo "doesn't exist"
fi

答案 2 :(得分:0)

这样的事情应该可以胜任:

if [[ $(ls img.*) ]]; then
  echo "file exist";
else
  echo "file does not exist";
fi

我建议看一下bash的模式匹配: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_03.html

答案 3 :(得分:0)

没有任何外部命令:

$ for i in img.*
> do
>  [ -f $i ] && echo exist || echo not exist
>  break
> done

检查是否存在任何文件。如果存在打印,则不存在,并立即中断。需要“-f”检查,因为如果没有文件存在,那么循环运行一次,其中i为“img。*”本身。

答案 4 :(得分:0)

shopt -s nullglob
files=( img.* )
if (( ${#files[@]} == 0 )); then
    echo "there are no 'img' files"
fi

如果你不使用nullglob那么,如果没有这样的文件,那么数组将有1个元素,即文字字符串“img。*”。