Skip to main content
2 of 4
Address the .tar.gz aspect.
Stephen Kitt
  • 482.8k
  • 60
  • 1.2k
  • 1.4k

You can use the shell’s parameter expansion modifiers:

$ pathname="/home/paulo/paulo.pdf" $ filename=${pathname##*/} $ printf "%s\n" "$filename" paulo.pdf $ basename=${filename%.*} $ printf "%s\n" "$basename" paulo 

${pathname##*/} is expanded to the contents of pathname, minus the longest prefix matching */, i.e. the full path (if there is one). ${filename%.*} is expanded to the contents of filename, minus the shortest suffix matching .*, i.e. the file’s extension (if there is one).

Note that this only removes the last filename component introduced by a dot; so paulo.tar.gz would become paulo.tar, not paulo. Strictly speaking the extension is .gz (it’s a compressed file, which happens to be a tarball; the .tar extension only becomes really meaningful once the file has been extracted).

Stephen Kitt
  • 482.8k
  • 60
  • 1.2k
  • 1.4k