如何在Shell脚本中删除文件名的扩展名? [英] How can I remove the extension of a filename in a shell script?
本文介绍了如何在Shell脚本中删除文件名的扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码有什么问题?
name='$filename | cut -f1 -d'.''
按原样,我得到了文字字符串$filename | cut -f1 -d'.'
,但是如果我删除引号,我什么也得不到.同时,输入
As is, I get the literal string $filename | cut -f1 -d'.'
, but if I remove the quotes I don't get anything. Meanwhile, typing
"test.exe" | cut -f1 -d'.'
在外壳中提供了我想要的输出,test
.我已经知道$filename
已分配了正确的值.我想做的就是将没有扩展名的文件名分配给变量.
in a shell gives me the output I want, test
. I already know $filename
has been assigned the right value. What I want to do is assign to a variable the filename without the extension.
推荐答案
You should be using the command substitution syntax $(command)
when you want to execute a command in script/command.
所以您的行应该是
name=$(echo "$filename" | cut -f 1 -d '.')
代码说明:
-
echo
获取变量$filename
的值并将其发送到标准输出 - 然后我们抓取输出并将其通过管道传输到
cut
命令 -
cut
将使用.作为将字符串切成段的定界符(也称为分隔符),并通过-f
选择要在输出中包含的段 - 然后
$()
命令替换将获取输出并返回其值 - 返回的值将分配给名为
name
的变量
echo
get the value of the variable$filename
and send it to standard output- We then grab the output and pipe it to the
cut
command - The
cut
will use the . as delimiter (also known as separator) for cutting the string into segments and by-f
we select which segment we want to have in output - Then the
$()
command substitution will get the output and return its value - The returned value will be assigned to the variable named
name
请注意,这将使变量的一部分一直到第一个周期.
:
Note that this gives the portion of the variable up to the first period .
:
$ filename=hello.world
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello.hello.hello
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello
$ echo "$filename" | cut -f 1 -d '.'
hello
这篇关于如何在Shell脚本中删除文件名的扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文