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 have the syntax wrong, or maybe substr isn't a function?
views:
516answers:
3
A:
filename sample.txt.pgp
returns sample.txt, I believe.
(use backticks)
Cheeso
2010-03-24 20:44:30
I don't think I've seen this command installed on any of my systems...
Jefromi
2010-03-24 20:52:28
@Jefromi: I think they're referring to `basename`.
Chris Jester-Young
2010-03-24 21:02:25
whoops, yes. basename
Cheeso
2010-03-24 21:23:13
`basename` is for stripping leading directory components. It can also remove suffixes, but only when you know what they are. `basename sample.txt.pgp .pgp` will print "sample.txt".
Jefromi
2010-03-24 22:39:20
+3
A:
a='sample.txt.pgp'
echo ${a%.*} # sample.txt (minimal match)
echo ${a%%.*} # sample (maximal match)
Chris Jester-Young
2010-03-24 20:44:57
This looks interesting... What's the dollar sign and % represent? Do you have a page that kinda explains this or anything?
TwixxyKit
2010-03-24 20:59:00
@KnockKnockWhosThere: Read http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 for more info. :-)
Chris Jester-Young
2010-03-24 21:00:44
And a more constrained version: `${a%.pgp}` only removes a `.pgp` extension if it is present; the original will remove any extension at all (which might be useful in some cases).
Jonathan Leffler
2010-03-24 21:27:14
+1
A:
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
Carl Norum
2010-03-24 21:08:28
Interesting that you use the '-s suffix' notation; that is not standardized by POSIX; the classic notation would be `$(basename $file .pgp)` (assuming the name is held in a variable '$file').
Jonathan Leffler
2010-03-24 21:25:44
@Jonathan Yes indeed! I just did a `man basename` on my OS X machine here, and saw the `-s` option; it was a bit more flexible (can handle more than one string), I didn't know it wasn't POSIX. I'll edit my answer.
Carl Norum
2010-03-24 21:40:00
Edited; I also put some double quotes in to support spaces in the filename.
Carl Norum
2010-03-24 21:41:59