bashfilenamescreation

Bash Basename Modification


Inside of bash I am loading a file such as:

/path/to/dir/filename.ext

now the idea is to use that file name and "extend its' name" upon modification such as:

some operation /path/to/dir/filename.ext > path/to/dir/filename_extendingfilename.ext;

So far I have managed to call the filename using this from another question that has already been asked on here (for reference Extract filename and extension in Bash) :

basename filename .extension

basename /path/to/dir/filename.txt .txt

filename

The issue im having is the creation of a new file which has the filename of the source file and extents on it using "_ extension.ext"


Solution

  • bash shell parameter expansion is an option here:

    f=/path/to/dir/filename.ext
    f2=${f%.ext*}"_extendingfilename.ext"
    

    The shell parameter expansion cuts at the last occurrence of .ext (i.e. it will also work correctly for a file like /path/to/dir/file.ext.name.ext)

    Here is an example for the redirection in the answer:

    f=/path/to/dir/filename.ext
    someoperation $f > ${f%.ext*}"_extendingfilename.ext"