下面是一个大脚本中的shell脚本片段。它从变量持有的字符串中删除引号。我正在使用sed,但它是有效的吗?如果不是,那么什么是有效的方法?

#!/bin/sh

opt="\"html\\test\\\""
temp=`echo $opt | sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/'`
echo $temp

当前回答

我使用这个正则表达式,避免从没有正确引用的字符串中删除引号,这里根据输入显示不同的输出,只有一个开始-结束引号受到影响:

echo '"only first' | sed 's/^"\(.*\)"$/\1/'

输出:>"only first<

echo 'only last"' | sed 's/^"\(.*\)"$/\1/'

输出:>"only last"<

echo '"both"' | sed 's/^"\(.*\)"$/\1/'

输出:> <

echo '"space after" ' | sed 's/^"\(.*\)"$/\1/'

输出:>"space after" <

echo ' "space before"' | sed 's/^"\(.*\)"$/\1/'

输出:> "space before"<

其他回答

还有另一种方法。如:

echo ${opt:1:-1}

使用xargs有一个简单的方法:

> echo '"quoted"' | xargs
quoted

如果没有提供命令,Xargs使用echo作为默认命令,并从输入中删除引号,参见这里的例子。但是请注意,这只在字符串不包含附加引号的情况下才有效。在这种情况下,它要么失败(引号数量不均匀),要么删除所有引号。

我使用这个正则表达式,避免从没有正确引用的字符串中删除引号,这里根据输入显示不同的输出,只有一个开始-结束引号受到影响:

echo '"only first' | sed 's/^"\(.*\)"$/\1/'

输出:>"only first<

echo 'only last"' | sed 's/^"\(.*\)"$/\1/'

输出:>"only last"<

echo '"both"' | sed 's/^"\(.*\)"$/\1/'

输出:> <

echo '"space after" ' | sed 's/^"\(.*\)"$/\1/'

输出:>"space after" <

echo ' "space before"' | sed 's/^"\(.*\)"$/\1/'

输出:> "space before"<

这是不使用sed的最离散的方式:

x='"fish"'
printf "   quotes: %s\nno quotes:  %s\n" "$x" "${x//\"/}"

Or

echo $x
echo ${x//\"/}

输出:

   quotes: "fish"
no quotes:  fish

我从线人那里得到的。

Bash中最简单的解决方案:

$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc

这被称为子字符串展开(参见Gnu Bash手册并搜索${parameter:offset:length})。在这个例子中,它从s获取子字符串,从位置1开始,到最后第二个位置结束。这是因为,如果length为负值,则它将被解释为从参数末尾开始的向后运行偏移。