TwixxyKit
TwixxyKit

Reputation: 10693

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 have the syntax wrong, or maybe substr isn't a function?

Upvotes: 1

Views: 5719

Answers (3)

Carl Norum
Carl Norum

Reputation: 224944

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

Upvotes: 2

C. K. Young
C. K. Young

Reputation: 223023

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

Upvotes: 3

Cheeso
Cheeso

Reputation: 192487

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

Upvotes: 0

Related Questions