如何在 bash 脚本中检查文件名的扩展名? [英] How to check the extension of a filename in a bash script?

查看:36
本文介绍了如何在 bash 脚本中检查文件名的扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 bash 编写每晚构建脚本.
除了一个小问题外,一切都很好:

I am writing a nightly build script in bash.
Everything is fine and dandy except for one little snag:


#!/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 文件.

My problem is determining the file extension and then acting accordingly. I know the issue is in the if-statement, testing for a txt file.

如何确定文件是否具有 .txt 后缀?

How can I determine if a file has a .txt suffix?

推荐答案

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

I think you want to say "Are the last four characters of $file equal to .txt?" If so, you can use the following:

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

请注意,file:-4 之间的空格是必需的,因为 ':-' 修饰符的含义不同.

Note that the space between file: and -4 is required, as the ':-' modifier means something different.

这篇关于如何在 bash 脚本中检查文件名的扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆