Bash:Filename
lastmod 2023-12-16created 2015-10-209 edits
A summary of how to manipulate filenames in Bash.
Example
Remove the path and extract the filename:
Remove an arbitrary extension:
More examples:
$ FILE=prog.tar.gz
$ echo ${FILE%%.*}
prog
$ echo ${FILE%.*}
prog.tar
$ echo ${FILE#*.}
tar.gz
$ echo ${FILE##*.}
gz
Example
if [[ -z $INPUT_PATH ]]; then
print_error "Input file is required"
exit 1
fi
INPUT_FILENAME="${INPUT_PATH##*/}"
INPUT_PARENT="${INPUT_PATH%/*}"
INPUT_NAME=${INPUT_FILENAME%.*}
INPUT_EXT=${INPUT_FILENAME#*.}
echo "$INPUT_PARENT"
echo "$INPUT_NAME"
echo "$INPUT_EXT"
Rename number
Renames files in numerical order.
$ IDX=1 && for i in *.jpg; do printf "%s\nmonero-01-%02d.jpg\n" "$i" "$IDX"; let "IDX = IDX + 1"; done | xargs -n 2 mv
Bash Function
Functions that find the extension, including a second extension such as tar.gz, and get the filename with the extension removed are as follows.
function getFileExtension {
local name=$1
local ext=`echo "${name#${name%.tar.*}}"`
if [[ -z $ext ]]; then
echo "${name#${name%.*}}"
else
echo $ext
fi
}
function getFileName {
local name=$1
local ext=`getFileExtension $name`
echo "${name%${ext}}"
}
Simple version
See also
Favorite site
- Extracting filenames and extensions - sh
- Extract File Basename Without Path and Extension in Bash
- The Right Way to Get the Directory of a bash Script 1
References
-
The_Right_Way_to_Get_the_Directory_of_a_bash_Script.pdf ↩
Pages that link here