Artanis
Artanis

Reputation: 11

Extract positional filename and extension in bash

I want to create a script that renames a file that has 2 extensions by deleting the midle extension. In reference to this, I found this great thread: Extract filename and extension in Bash

Someone posted there this in regards to shell parameter extension:

~% FILE="example.tar.gz"
~% echo "${FILE%%.*}"
example
~% echo "${FILE%.*}"
example.tar
~% echo "${FILE#*.}"
tar.gz
~% echo "${FILE##*.}"
gz

My question is on the above statement: how do you echo example.gz ?

Thanks

Upvotes: 1

Views: 65

Answers (2)

Pac0
Pac0

Reputation: 23174

You can simply achieve it without any temporary variable, by combining the correct statements that gives the 2 parts you need with a .in between :

echo "${FILE%%.*}.${FILE##*.}"

Upvotes: 1

chepner
chepner

Reputation: 531868

You can't do it on one operation; you need to use temporary variables.

$ ext=${FILE##*.} # ext=gz
$ tmp=${FILE%.*}  # Remove .gz
$ echo "${tmp%.*}.$ext"  # Remove .tar, then add .gz back

Upvotes: 1

Related Questions