[英]Unix substr in shell script?
I have a string like sample.txt.pgp and I want to return sample.txt in a shell script (but, the string length will vary, so, basically all of the characters before the ".pgp"). 我有一个像sample.txt.pgp这样的字符串,我想在shell脚本中返回sample.txt(但是,字符串的长度会有所不同,因此,基本上所有在“ .pgp”之前的字符)。 Is there a substr function?
有substr函数吗? Like, if I did
substr('sample.txt.pgp', -4, 0)
, is it supposed to return sample.txt? 就像,如果我做了
substr('sample.txt.pgp', -4, 0)
,它应该返回sample.txt吗? Right now it isn't, so I'm wondering if I have the syntax wrong, or maybe substr isn't a function? 现在不是,所以我想知道语法是否错误,或者substr不是函数吗?
a='sample.txt.pgp'
echo ${a%.*} # sample.txt (minimal match)
echo ${a%%.*} # sample (maximal match)
You can use basename
: 您可以使用
basename
:
$ basename sample.txt.pgp .pgp
sample.txt
Use backticks or $()
to put the result in a variable if you want: 如果需要,请使用反引号或
$()
将结果放入变量中:
$ FILE=sample.txt.pgp
$ VARIABLE=$(basename "$FILE" .pgp)
$ echo $VARIABLE
sample.txt
filename sample.txt.pgp
returns sample.txt, I believe. 我相信,
filename sample.txt.pgp
返回sample.txt。 (use backticks) (使用反引号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.