Removing extension from filename in bash

This is a very post, but things must be learned and writing down them is the better way. The title Removing extension from filename in bash is just a pretext. However for who need a very quick solution:

~ $ completeFile=test.txt
~ $ echo $completeFile
test.txt
~ $ filename="${completeFile%.*}"
~ $ echo $filename
test

At line 4 you will find the solution at your problem. But we can talk about that line a little bit, introducing some interesting things on Manipulating String in Bash.

Well, the interesting part of that command is the %. The symbol % delete the

shortest match of $substring from back of $string

You have to think at command as ${string%substring}. This makes things more clear: $string is the complete string to modify, while the $substring is the part of the string that you want to delete.
The way to parse the string is defined by default, % acts as a right filter, so it starts from the right to parse.

From the example the $substring is everything after the point.

At the same time, another useful symbol is # because it acts like % but from the front of the $string. Thus, the command ${string#substring}

deletes the shortest match of $substring from the front of $string

.

From the previous example:

because the $substring in this case, is everything before the point.

Concluding, while % acts for suffixes, # acts for prefixes.

#gwh

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

About Francesco Serafin

I am a PhD student at the Department of Civil, Environmental and Mechanical Engineering at the University of Trento. My two greatest loves: Computer Science and Water (take three with my Lenovo!:D). As a result, the aim of my life is to make both passions coexist. My gpg public key available at https://pgp.mit.edu

Leave a Reply

Your email address will not be published.

*