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

有帮助吗?

解决方案

我想你想说<!> quot; $ file的最后四个字符是否等于.txt?<!> quot;如果是这样,您可以使用以下内容:

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

请注意,file:-4之间的空格是必需的,因为': - '修饰符意味着不同的东西。

其他提示

制作

if [ "$file" == "*.txt" ]
像这样:

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

即双括号,无引号。

==的右侧是一个shell模式。 如果您需要正则表达式,请使用=~然后。

你无法确定在Unix系统上,.txt文件确实是一个文本文件。你最好的选择是使用<!> quot; file <!> quot;。也许尝试使用:

file -ib "$file"

然后,您可以使用MIME类型列表来匹配或解析MIME的第一部分,其中包含<!> quot; text <!> quot;,<!> quot; application <!> quot ;等等。

您可以使用<!>“;文件<!>”;命令,如果您确实想要找到有关该文件的信息而不是依赖于扩展名。

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

你也可以这样做:

   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

我写了一个bash脚本,查看文件的类型,然后将其复制到某个位置,我用它来查看我在火狐缓存中在线观看的视频:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

它使用与此处提供的相似的想法,希望这对某人有帮助。

我猜'$PATH_TO_SOMEWHERE'就像'<directory>/*'

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

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 ...

关于如何在linux中使用文件名中的扩展名的正确答案是:

${strFileName##*\\.} 

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

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

我的剪切

>cut -d'.' -f2<<<"hi_mom.txt"
txt

我对awk的看法将如下所示。

>MY_DATA_FILE="my_file.sql"
>FILE_EXT=$(awk -F'.' '{print $NF}' <<< $MY_DATA_FILE)
>if [ "sql" = "$FILE_EXT" ]
>then
>   echo "file is sql"
>fi

>awk -F'.' '{print $NF}' <<eof
>hi_mom.txt
>my_file.jpg
>eof
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top