如何在 shell 脚本中删除文件名的扩展名?
下面的代码有什么问题?
What's wrong with the following code?
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'.'
在 shell 中给我我想要的输出,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.
您应该使用 命令替换 语法$(command)
当你想在脚本/命令中执行命令时.
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