简体   繁体   中英

How to get extension of a file in shell script

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.

to get file extension, just use the shell

$ filename="myfile.ext"
$ echo ${filename##*.}
ext
$ file_ext=${filename##*.} #put to variable
$ echo ${file_ext}
ext

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM