LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   bash: best way to get filename and extension using bash (http://www.linuxquestions.org/questions/programming-9/bash-best-way-to-get-filename-and-extension-using-bash-781090/)

frenchn00b 01-09-2010 12:59 PM

bash: best way to get filename and extension using bash
 
I would like to get the filename (without extension) and the extension separately.

The best solution I found so far is:

Let FILE="thefilenameofsomefilesfor_instance.txt"
Code:

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

I think it would be better to count the len and remove 3 chars to right to get the extension, but it can be macintosh filenames with have 4 chars for extensions, and this can be hazardous

GrapefruiTgirl 01-09-2010 01:04 PM

There are likely a stack of ways to do the same; is there anything in particular you don't like about the way you have used above? You could use awk or sed too, but the way you used is probably no better or worse, unless you're considering the difference in nanoseconds that each particular method uses (time to do the operation), in which case cut is probably faster than awk but similar to sed.

Faster yet again, might be ${bash/substitution/substitution} if you are always using bash shell. Check the man page for details on this.

GooseYArd 01-09-2010 01:17 PM

Check out the basename command. Once you have the basename you can sed out the extension.

alunduil 01-09-2010 01:24 PM

Check out the handy features at The Advanced BASH Scripting Guide.

Code:

filename="something.extension"
basename=${filename%.*}
extension=${filename##*.}

Regards,

Alunduil

GooseYArd 01-09-2010 01:26 PM

Quote:

Originally Posted by alunduil (Post 3820429)
Code:

filename="something.extension"
basename=${filename%.*}
extension=${filename##*.}

Alunduil

huge fan. im getting that one tattooed on my arm.

alunduil 01-09-2010 01:47 PM

I have plenty more obscure BASH scripts if you need more tattoos. Those aren't even the fun ones ... lol. Hope that helped out the OP.

Regards,

Alunduil


All times are GMT -5. The time now is 03:31 AM.