我正在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的最后四个字符是否等于。txt?”如果是,你可以使用以下方法:

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

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

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

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

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

如何在linux中获取可用的扩展名的正确答案是:

${filename##*\.} 

打印目录中所有文件扩展名的示例

for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir
    do  echo ${fname##*\.} #print extensions 
done

在Unix系统中,您无法确定.txt文件是否真的是文本文件。你最好使用“file”。也许可以试试:

file -ib "$file"

然后,您可以使用MIME类型列表来匹配或解析MIME的第一部分,在那里您可以获得诸如“文本”,“应用程序”等内容。

你还可以:

   if [ "${FILE##*.}" = "txt" ]; then
       # operation for txt files here
   fi