下面的代码有什么问题?

name='$filename | cut -f1 -d'.''

就像这样,我得到的字面值字符串$filename | cut -f1 -d'。',但如果我删除引号,我什么也得不到。与此同时,打字

"test.exe" | cut -f1 -d'.'

在shell中给出我想要的输出,test。我已经知道$filename已经被分配了正确的值。我要做的是给一个变量分配没有扩展名的文件名。


当前回答

如果你的文件名包含一个点(除了扩展名),那么使用这个:

echo $filename | rev | cut -f 2- -d '.' | rev

其他回答

#!/bin/bash
filename=program.c
name=$(basename "$filename" .c)
echo "$name"

输出:

program

你的代码有两个问题:

您使用' (tick)而不是'(反tick)来包围生成想要存储在变量中的字符串的命令。 您没有将变量“$filename”“echo”到管道中的“cut”命令中。

我会把你的代码改为"name= ' echo $filename | cut -f 1 -d '。' ' ",如下所示(再次注意,后面的勾号围绕着name变量定义):

$> filename=foo.txt
$> echo $filename
foo.txt
$> name=`echo $filename | cut -f1 -d'.'`
$> echo $name
foo
$> 

仅使用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 "$oneextless" 

# 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"

打印输出的演示:

this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename
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

你想用哪个就用哪个。这里我假设是最后一个。(点)后面跟着文本是扩展。

如果你的文件名包含一个点(除了扩展名),那么使用这个:

echo $filename | rev | cut -f 2- -d '.' | rev