我正在bash中编写夜间构建脚本。 一切都很好,除了一个小障碍:

#!/bin/bash

for file in "$PATH_TO_SOMEWHERE"; do
      if [ -d $file ]
      then
              # do something directory-ish
      else
              if [ "$file" == "*.txt" ]       #  this is the snag
              then
                     # do something txt-ish
              fi
      fi
done;

我的问题是确定文件扩展名,然后进行相应的操作。我知道问题在if语句中,测试txt文件。

如何确定文件后缀为。txt ?


当前回答

这个答案的大部分归功于@Jox,尽管我发现(js)匹配的是.json文件,所以我添加了一个eol字符,以更充分地匹配扩展名。

$file不需要加引号,因为[[]]不会展开,所以空格不是问题(来源:Hontvári Levente)

if [[ $file =~ .*\.(js$|json$) ]]; then
  echo "The extension of '$file' matches .js|.json";
fi

其他回答

如果您实际上想要查找有关文件的信息,而不是依赖于扩展名,则可以使用“file”命令。

如果您对使用扩展感到满意,您可以使用grep来查看它是否匹配。

我猜'$PATH_TO_SOMEWHERE'是类似于'<目录>/*'。

在这种情况下,我将代码更改为:

find <directory> -maxdepth 1 -type d -exec ... \;
find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;

如果你想对目录和文本文件名做一些更复杂的事情,你可以:

find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done

如果文件名中有空格,你可以:

find <directory> -maxdepth 1 -type d | xargs ...
find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...

另一个重要的细节是,你不能在内部使用else和另一个if:

else
    if [ "$file" == "*.txt" ]       
    #  this is the snag
    then
    # do something txt-ish
fi

而不是:

elif [ "$file" == "*.txt" ]       
    #  this is the snag
then
    # do something txt-ish
fi

Else在没有其他命令时使用

仅仅因为你能做某件事,并不意味着你应该一直做下去

我认为你想说“$file的最后四个字符是否等于。txt?”如果是,你可以使用以下方法:

if [ "${file: -4}" == ".txt" ]

注意,file:和-4之间的空格是必需的,因为':-'修饰符的含义不同。

类似于'file',使用稍微简单一点的'mimetype -b',无论文件扩展名是什么都可以。

if [ $(mimetype -b "$MyFile") == "text/plain" ]
then
  echo "this is a text file"
fi

编辑:如果mimetype不可用,您可能需要在系统上安装libfile-mimeinfo-perl