用于检查文件名的bash脚本以期望的字符串开头 [英] bash script to check file name begins with expected string

查看:208
本文介绍了用于检查文件名的bash脚本以期望的字符串开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用bash脚本在OS X上运行:

Running on OS X with a bash script:

sourceFile=`basename $1`
shopt -s nocasematch
if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi

以上情况有效,但如果用户提供名为 adUsers_new的文件该怎么办? .txt

The above works, but what if the user sources a file called adUsers_new.txt?

我试过:

if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success ; else echo fail ; fi

但在这种情况下,通配符不起作用。
我正在编写此脚本以允许用户对源文件名进行不同的迭代,必须以 aduser 开头,并且 .txt 文件扩展名。

But the wildcard doesn't work in this case. I'm writing this script to allow for the user to have different iterations of the source file name, which must begin with aduser and have the .txt file extension.

推荐答案

bash ,你可以得到一个shell变量的前7个字符:

In bash, you can get the first 7 characters of a shell variable with:

${sourceFile:0:7}

和最后四个:

${sourceFile:${#sourceFile}-4}

有了这些知识,只需使用那些你通常会使用变量本身的表达式,如下面的脚本:

Armed with that knowledge, simply use those expressions where you would normally use the variable itself, something like the following script:

arg=$1
shopt -s nocasematch
i7f4="${arg:0:7}${arg:${#arg}-4}"
if [[ "${i7f4}" = "adusers.txt" ]] ; then
    echo Okay
else
    echo Bad
fi

您可以使用以下成绩单查看它:

You can see it in action with the following transcript:

pax> check.sh hello
Bad

pax> check.sh addUsers.txt
Bad

pax> check.sh adUsers.txt
Okay

pax> check.sh adUsers_new.txt
Okay

pax> check.sh aDuSeRs_stragngeCase.pdf.gx..txt
Okay

这篇关于用于检查文件名的bash脚本以期望的字符串开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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