It is quite common knowledge that the
basename command is used to get just the file name without its full path.
> basename /home/$USER/file.txt file.txt
But what wasn’t common knowledge, at least to me, was that
basename also accepts a second argument ..
That argument is used to specify the trailing string to be removed from first argument.
man basename, we get
DESCRIPTION Print NAME with any leading directory components removed. If specified, also remove a trailing SUFFIX. EXAMPLES basename /usr/bin/sort Output "sort". basename include/stdio.h .h Output "stdio".
In other words, with the second argument set to the file’s extension,
basename returns the file name without the full path and without the extension.
> basename /home/$USER/file.txt .txt file
I came across this feature of
basename when I wanted to create this tcsh alias:
# Usage: md2 html file.md # Converts file.md (markdown) to file.html # md2 pdf file.md # Converts file.md (markdown) to file.pdf # md2 docx file.md # Converts file.md (markdown) to file.docx (Word) alias md2 'pandoc \!:3* \!:2 -o `basename \!:2 .md`.\!:1'