[英]How to get extension of a file in shell script
I am trying to get file extension for a file in shell script.我正在尝试获取 shell 脚本中文件的文件扩展名。 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.但是这两个命令都未能将值放入变量 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.我是 shell 脚本的新手。 Please describe the situation what is happening.请描述正在发生的情况。 And also how should I do it?还有我该怎么做?
Thanks.谢谢。
to get file extension, just use the shell要获取文件扩展名,只需使用 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: [编辑] Martin 的更好建议:
file_ext=$(printf '%s' "$filename" | awk -F . '{if (NF>1) {print $NF}}')
That will store in $file_ext
the output of the command.这会将命令的输出存储在$file_ext
中。
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.请注意,您不能在变量后放置空格,因为这样它就会被解释为普通命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.