如何在 shell 脚本中删除文件名的扩展名? [英] How can I remove the extension of a filename in a shell script?

查看:133
本文介绍了如何在 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 '.')

代码说明:

  1. echo 获取变量 $filename 的值并将其发送到标准输出
  2. 然后我们获取输出并将其传送到 cut 命令
  3. cut 将使用 .作为分隔符(也称为分隔符),用于将字符串切割成段,并通过 -f 我们选择我们想要在输出中包含的段
  4. 然后 $() 命令替换将获得输出并返回其值
  5. 返回值将赋值给名为name
  6. 的变量
  1. echo get the value of the variable $filename and send it to standard output
  2. We then grab the output and pipe it to the cut command
  3. 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
  4. Then the $() command substitution will get the output and return its value
  5. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆