在Bash中获取文件扩展名

SigGP

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

费德里科·卡帕尔多(Federico Capaldo)

似乎您只是在问如何将文件名的文件扩展名放入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->获取扩展名,txtfile.odt.pdf->获取扩展名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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章