mim*_*pus 121 bash shell cut sh gnu-coreutils
以下代码有什么问题?
name='$filename | cut -f1 -d'.''
Run Code Online (Sandbox Code Playgroud)
因为,我得到文字字符串$filename | cut -f1 -d'.'
,但如果我删除引号,我什么都没得到.同时打字
"test.exe" | cut -f1 -d'.'
Run Code Online (Sandbox Code Playgroud)
在shell中给我输出我想要的输出test
.我已经知道$filename
已经分配了正确的价值.我想要做的是为变量分配没有扩展名的文件名.
che*_*ner 212
您还可以使用参数扩展:
$ filename=foo.txt
$ echo "${filename%.*}"
foo
Run Code Online (Sandbox Code Playgroud)
小智 99
如果您知道扩展名,则可以使用basename
$ basename /home/jsmith/base.wiki .wiki
base
Run Code Online (Sandbox Code Playgroud)
Roh*_*han 95
如果要在脚本/命令中执行命令,则应使用命令替换语法$(command)
.
所以你的路线就是
name=$(echo "$filename" | cut -f 1 -d '.')
Run Code Online (Sandbox Code Playgroud)
代码说明:
echo
获取变量的值$filename
并将其发送到标准输出cut
命令cut
会使用.作为分隔符(也称为分隔符),用于将字符串切割成段,并通过-f
我们选择输出中要包含的段$()
命令替换将获得输出并返回其值name
请注意,这会将变量的部分提供给第一个句点.
:
$ 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
Run Code Online (Sandbox Code Playgroud)
man*_*h_s 17
如果您的文件名包含一个点(扩展名除外),请使用以下命令:
echo $filename | rev | cut -f 2- -d '.' | rev
Run Code Online (Sandbox Code Playgroud)
小智 17
file1=/tmp/main.one.two.sh
t=$(basename "$file1") # output is main.one.two.sh
name=$(echo "$file1" | sed -e 's/\.[^.]*$//') # output is /tmp/main.one.two
name=$(echo "$t" | sed -e 's/\.[^.]*$//') # output is main.one.two
Run Code Online (Sandbox Code Playgroud)
使用你想要的任何一个.这里我假设最后.
(点)后跟文本是扩展名.
Léa*_*ris 13
仅使用 POSIX 的内置:
#!/usr/bin/env sh
path=this.path/with.dots/in.path.name/filename.tar.gz
# Get the basedir without external command
# by stripping out shortest trailing match of / followed by anything
dirname=${path%/*}
# Get the basename without external command
# by stripping out longest leading match of anything followed by /
basename=${path##*/}
# Strip uptmost trailing extension only
# by stripping out shortest trailing match of dot followed by anything
oneextless=${basename%.*}; echo "$noext"
# Strip all extensions
# by stripping out longest trailing match of dot followed by anything
noext=${basename%%.*}; echo "$noext"
# Printout demo
printf %s\\n "$path" "$dirname" "$basename" "$oneextless" "$noext"
Run Code Online (Sandbox Code Playgroud)
打印演示:
this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename
Run Code Online (Sandbox Code Playgroud)
小智 7
#!/bin/bash
file=/tmp/foo.bar.gz
echo $file ${file%.*}
Run Code Online (Sandbox Code Playgroud)
输出:
/tmp/foo.bar.gz /tmp/foo.bar
Run Code Online (Sandbox Code Playgroud)
请注意,仅删除了最后一个扩展名。