开发者

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"). Is there a substr function? Like, if I did substr('sample.txt.pgp', -4, 0), is it supposed to return sample.txt? Right now it isn't, so I'm wondering if I开发者_如何学JAVA have the syntax wrong, or maybe substr isn't a function?


a='sample.txt.pgp'
echo ${a%.*}   # sample.txt (minimal match)
echo ${a%%.*}  # sample     (maximal match)


You can use 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. (use backticks)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜