在Bash

时间:2017-05-27 12:57:55

标签: string bash filenames

我正在编写一个脚本,它将按扩展名对文件进行排序。我知道一种方法可以通过文件名来实现。问题是,相同的文件名称中没有扩展名。例如,如果我有文件:file.txt,则通过简单extension="${filename##*.}"获取扩展程序没有问题。但如果文件名只是filename,则此方法不起作用。是否还有其他选项可以获取文件的扩展名并将其放入Bash脚本中变量?

5 个答案:

答案 0 :(得分:5)

没有像[[这样的基本原理:

case $filename in
  (*.*) extension=${filename##*.};;
  (*)   extension="";;
esac

适用于任何Bourne-heritage shell。

答案 1 :(得分:2)

filename="file.txt"
ext="${filename##*.}"
if [[ "$ext" != "$filename" ]]; then echo "$ext"; else echo "no extension"; fi

输出:

txt
filename="file"
ext="${filename##*.}"
if [[ "$ext" != "$filename" ]]; then echo "$ext"; else echo "no extension"; fi

输出:

no extension

答案 2 :(得分:2)

您可以通过删除扩展程序获取文件的基本名称,从原文中删除

base=${filename%.*}
ext=${filename#$base.}

我更喜欢case声明;意图更清晰。

答案 3 :(得分:1)

对于以下情况:

$ ls file*
file1  file1.txt  file2  

您可以执行以下操作:

$ ls file* |awk -F. '{print (NF>1?$NF:"no extension")}'
no extension
txt
no extension

答案 4 :(得分:0)

您似乎只是询问如何将文件名的文件扩展名放入bash中的变量中,而您不会询问排序部分。 为此,以下简要脚本可以从文件列表中打印每个文件的扩展名。

#!/bin/sh
filesInCurrentDir=`ls`
for file in $filesInCurrentDir; do
    extention=`sed 's/^\w\+.//' <<< "$file"`
    echo "the extention for $file is: "$extention #for debugging
done

包含所分析的当前文件的扩展名的变量称为extention。命令sed 's/^\w\+.//匹配任意长度的字符,直到在文件名中找到第一个点,然后将其删除。因此,如果有多个文件扩展名,则会全部列出(例如file.txt - &gt;获取扩展名txt,但file.odt.pdf - &gt;获取扩展名odt.pdf)。

实施例

当前文件夹内容(这可以是您提供给循环的任何以空格分隔的文件列表)

aaab.png
abra
anme2.jpg
cadabra
file
file.png
file.txt
loacker.png
myText
name.pdf
rusty.jgp

以上脚本的结果:

the extention of aaab.png is: png
the extention of abra is: 
the extention of anme2.jpg is: jpg
the extention of cadabra is: 
the extention of file is: 
the extention of file.png is: png
the extention of file.txt is: txt
the extention of loacker.png is: png
the extention of myText is: 
the extention of name.pdf is: pdf
the extention of rusty.jgp is: jgp

这样,没有扩展名的文件将导致扩展变量为空。