views:

516

answers:

3

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?

A: 

filename sample.txt.pgp returns sample.txt, I believe. (use backticks)

Cheeso
I don't think I've seen this command installed on any of my systems...
Jefromi
@Jefromi: I think they're referring to `basename`.
Chris Jester-Young
whoops, yes. basename
Cheeso
`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
+3  A: 
a='sample.txt.pgp'
echo ${a%.*}   # sample.txt (minimal match)
echo ${a%%.*}  # sample     (maximal match)
Chris Jester-Young
This looks interesting... What's the dollar sign and % represent? Do you have a page that kinda explains this or anything?
TwixxyKit
@KnockKnockWhosThere: Read http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 for more info. :-)
Chris Jester-Young
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
+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
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
@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
Edited; I also put some double quotes in to support spaces in the filename.
Carl Norum
Ah, thank you very much!
TwixxyKit