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


当前回答

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

其他回答

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

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

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

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

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

file -ib "$file"

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

另一个重要的细节是,你不能在内部使用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之间的空格是必需的,因为':-'修饰符的含义不同。