Skip to content
Search

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:

$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt

Remove an arbitrary extension:

$ s=foo.txt
$ echo ${s%.*}
foo

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

$ FILE=prog.tar.gz.double
$ echo ${FILE%%.*}
prog
$ echo ${FILE#*.}
tar.gz.double

See also

Favorite site

References


  1. The_Right_Way_to_Get_the_Directory_of_a_bash_Script.pdf ↩

author Zer0 sitemap