下面是一个大脚本中的shell脚本片段。它从变量持有的字符串中删除引号。我正在使用sed,但它是有效的吗?如果不是,那么什么是有效的方法?
#!/bin/sh
opt="\"html\\test\\\""
temp=`echo $opt | sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/'`
echo $temp
下面是一个大脚本中的shell脚本片段。它从变量持有的字符串中删除引号。我正在使用sed,但它是有效的吗?如果不是,那么什么是有效的方法?
#!/bin/sh
opt="\"html\\test\\\""
temp=`echo $opt | sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/'`
echo $temp
当前回答
Bash中最简单的解决方案:
$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc
这被称为子字符串展开(参见Gnu Bash手册并搜索${parameter:offset:length})。在这个例子中,它从s获取子字符串,从位置1开始,到最后第二个位置结束。这是因为,如果length为负值,则它将被解释为从参数末尾开始的向后运行偏移。
其他回答
STR='"0.0.0"' ## OR STR="\"0.0.0\""
echo "${STR//\"/}"
## Output: 0.0.0
我使用这个正则表达式,避免从没有正确引用的字符串中删除引号,这里根据输入显示不同的输出,只有一个开始-结束引号受到影响:
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 | sed "s/\"//g"
它实际上从opt中删除了所有的“s(双引号)(除了开头和结尾之外,真的会有更多的双引号吗?所以这实际上是一样的事情,更简短;-))
Linux=`cat /etc/os-release | grep "ID" | head -1 | awk -F= '{ print $2 }'`
echo $Linux
Output:
"amzn"
从变量中删除双引号的最简单方法是
Linux=`echo "$Linux" | tr -d '"'`
Linux=$(eval echo $Linux)
Linux=`echo ${Linux//\"/}`
Linux=`echo $Linux | xargs`
All提供不带双引号的输出:
echo $ Linux
amzn
更新
仅使用bash /标准Linux命令剥离字符串中的单引号和双引号的简单而优雅的答案:
BAR=$(eval echo $BAR)从BAR中删除引用。
=============================================================
根据hueybois的答案,经过反复试验,我得出了这个函数:
function stripStartAndEndQuotes {
cmd="temp=\${$1%\\\"}"
eval echo $cmd
temp="${temp#\"}"
eval echo "$1=$temp"
}
如果你不希望输出任何东西,你可以将计算结果输出到/dev/null 2>&1。
用法:
$ BAR="FOO BAR"
$ echo BAR
"FOO BAR"
$ stripStartAndEndQuotes "BAR"
$ echo BAR
FOO BAR