小能豆

Extract filename and extension in Bash

javascript

I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`

This is wrong because it doesn’t work if the file name contains multiple . characters. If, let’s say, I have a.b.js, it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path)

but I’d prefer not to fire up a Python interpreter just for this, if possible.

Any better ideas?


阅读 229

收藏
2023-12-28

共1个答案

小能豆

In Bash, you can use parameter expansion to achieve this without invoking external commands like cut. Here’s an example:

FILE="a.b.js"

# Get the extension
EXTENSION="${FILE##*.}"

# Get the filename (without extension)
NAME="${FILE%.*}"

echo "Filename: $NAME"
echo "Extension: $EXTENSION"

This uses the ##*. and %.* patterns for parameter expansion, where ##*. removes the longest match of *. from the beginning (leaving only the extension), and %.* removes the shortest match of .* from the end (leaving only the filename without extension).

This approach is more efficient and handles multiple dots in the filename correctly.

2023-12-28