我正在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 ?


当前回答

你还可以:

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

其他回答

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

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

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

我猜'$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 ...

你还可以:

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

使

if [ "$file" == "*.txt" ]

是这样的:

if [[ $file == *.txt ]]

也就是说,只有双括号,没有引号。

==的右侧是一个外壳模式。 如果需要正则表达式,则使用=~ then。

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

${filename##*\.} 

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

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