joereynolds / what-to-code

Ideas for things to program
MIT License
1.44k stars 63 forks source link

A command-line utility that gets the extension of a file #24

Closed msiism closed 4 years ago

msiism commented 4 years ago

How about a bit of POSIX shell?

$ cat $HOME/gex
gex() {
  # Get file extension

  (for f in "$@"
  do
    case "$f" in
    ?*.?*)
      printf '%s\n' "${f##*.}"
    ;;
    esac
  done)
}
$ . $HOME/gex
$ ls
foo.bar  hello.jpg  myfile.test.php  the_thing.tar.bz2
$ gex hello.jpg myfile.test.php 
jpg
php
$ gex *
bar
jpg
php
bz2

Oh, well... What's a file extension, anyway? And why would you need a dedicated tool to extract it from a file name?

joereynolds commented 4 years ago

Hey @msiism,

Whatever a file extension is, you inferred it from the description correctly. I'd say it was the suffix on a filename following the '.'. Thanks!