Answer a question

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.

Answers

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.

Logo

更多推荐