我正在用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;
Run Code Online (Sandbox Code Playgroud)
我的问题是确定文件扩展名,然后相应地采取行动.我知道问题出在if语句中,测试txt文件.
如何确定文件后缀是否为.txt?
小智 243
使
if [ "$file" == "*.txt" ]
Run Code Online (Sandbox Code Playgroud)
像这样:
if [[ $file == *.txt ]]
Run Code Online (Sandbox Code Playgroud)
也就是说,双括号,没有引号.
右侧==是贝壳图案.如果需要正则表达式,请使用=~.
Pau*_*son 224
我想你想说"$ file的最后四个字符是否等于.txt?" 如果是这样,您可以使用以下内容:
if [ ${file: -4} == ".txt" ]
Run Code Online (Sandbox Code Playgroud)
需要注意的是之间的空间file:和-4需要,为" - "修饰符意味着不同的东西.
Eld*_*ell 26
你不能确定在Unix系统上,.txt文件确实是一个文本文件.你最好的选择是使用"文件".也许尝试使用:
file -ib "$file"
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用MIME类型列表来匹配或解析MIME的第一部分,您可以在其中获取"text","application"等内容.
kvz*_*kvz 15
你也可以这样做:
if [ "${FILE##*.}" = "txt" ]; then
# operation for txt files here
fi
Run Code Online (Sandbox Code Playgroud)
小智 11
关于如何在 linux 中获取文件名中可用扩展名的正确答案是:
${filename##*\.}
Run Code Online (Sandbox Code Playgroud)
打印目录中所有文件扩展名的示例
for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir
do echo ${fname##*\.} #print extensions
done
Run Code Online (Sandbox Code Playgroud)
与'file'类似,使用稍微简单的'mimetype -b',无论文件扩展名如何,都可以使用.
if [ $(mimetype -b "$MyFile") == "text/plain" ]
then
echo "this is a text file"
fi
Run Code Online (Sandbox Code Playgroud)
编辑:如果mimetype不可用,您可能需要在系统上安装libfile-mimeinfo-perl
| 归档时间: |
|
| 查看次数: |
198478 次 |
| 最近记录: |