1

In my script I'm trying to take a string, then output the extension of a string if it has one. So essentially I take the basename of a file, then output anything that comes after a period.

What's the syntax to do something like this?

For example

dotcutter.sh
file=testfile.jpg

the script should output .jpg

EDIT:

I've solved my problem now with:

file=$(basename "$1" )
stub=${file%.*}
echo ${file#"$stub"}

Which reduces my argument to a basename, thank you all.

1

2 Answers 2

3
$ file=testfile.jpg
$ echo ${file##*.}
jpg
$ file=testfile.ext1.ext2
$ echo ${file##*.}
ext2
$ file=noextension
$ echo ${file##*.}
noextension

Notice that it doesn't work if the file has no extension. If that's important then try this two-step solution:

$ file=testfile.ext1.ext2
$ stub=${file%.*}
$ echo ${file#"$stub"}
.ext2

Or this regex-based one, which will only call echo if there's actually an extension. (&& is shorthand for "if then".)

$ regex='(\.[^.]*)$'
$ file=testfile.ext1.ext2
$ [[ $file =~ $regex ]] && echo ${BASH_REMATCH[1]}
.ext2
$ file=noextension
$ [[ $file =~ $regex ]] && echo ${BASH_REMATCH[1]}

See also:

  • basename(1)
  • dirname(1)
  • Bash FAQ: How can I use parameter expansion? How can I get substrings? How can I get a file without its extension, or get just a file's extension?]
4
  • Could you explain for me, what specifically each part of $ stub=${file%.*} $ echo ${file#"$stub"} does?
    – Unknown
    Oct 11, 2012 at 16:28
  • @BernieMacinflor The first line deletes the extension .* and stores just the file name in $stub. The second part deletes $stub from $file, which leaves the extension to be echoed. Oct 11, 2012 at 17:00
  • Thank you, I'm new to Bash and the syntax always seems very random and confusing.
    – Unknown
    Oct 11, 2012 at 17:05
  • @BernieMacinflor Sure, here to help! For more details look up "Parameter Expansion" in man bash. Oct 11, 2012 at 22:22
1

Try the following code :

file=testfile.jpg
echo .${file#*.}

That use parameter expansion

3
  • That only removes up to the first period, if there are more than one in the file name. Use ${file##*.}.
    – chepner
    Oct 9, 2012 at 20:04
  • Typically extensions have only one period. Moreover, this is what OP asked. Oct 9, 2012 at 20:30
  • I'm thinking of file names like 'foo.tar.gz'. Is the extension 'gz' or 'tar.gz'?
    – chepner
    Oct 9, 2012 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.