Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get extension of a file in shell script

Tags:

linux

shell

I am trying to get file extension for a file in shell script. But without any luck.

The command I am using is

file_ext=${filename##*.}

and

file_ext = $filename |awk -F . '{if (NF>1) {print $NF}}'

But both of the commands failed to put value in variable file_ext. But when i try

echo $filename |awk -F . '{if (NF>1) {print $NF}}'

It gives me the desired result. I am new to shell script. Please describe the situation what is happening. And also how should I do it?

Thanks.

like image 717
vijay.shad Avatar asked Feb 28 '10 19:02

vijay.shad


3 Answers

to get file extension, just use the shell

$ filename="myfile.ext"
$ echo ${filename##*.}
ext
$ file_ext=${filename##*.} #put to variable
$ echo ${file_ext}
ext
like image 130
ghostdog74 Avatar answered Oct 23 '22 15:10

ghostdog74


Spaces hurt.

Anyway you should do:

file_ext=$(echo $filename | awk -F . '{if (NF>1) {print $NF}}')

[Edit] Better suggestion by Martin:

file_ext=$(printf '%s' "$filename" | awk -F . '{if (NF>1) {print $NF}}')

That will store in $file_ext the output of the command.

like image 27
Enrico Carlesso Avatar answered Oct 23 '22 14:10

Enrico Carlesso


You have to be careful when declaring variables.

variable1="string"    # assign a string value
variable3=`command`   # assign output from command
variable2=$(command)  # assign output from command

Notice that you cannot put a space after the variable, because then it gets interpreted as a normal command.

like image 3
Otto Allmendinger Avatar answered Oct 23 '22 13:10

Otto Allmendinger