Shell脚本-从变量中删除第一引号和最后引号(“) [英] Shell script - remove first and last quote (") from a variable

查看:843
本文介绍了Shell脚本-从变量中删除第一引号和最后引号(“)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是较大脚本中的Shell脚本的片段.它从由变量保存的字符串中删除引号.我正在使用sed进行操作,但是效率高吗?如果没有,那么有效的方法是什么?

Below is the snippet of a shell script from a larger script. It removes the quotes from the string that is held by a variable. I am doing it using sed, but is it efficient? If not, then what is the efficient way?

#!/bin/sh

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

推荐答案

使用本机shell前缀/后缀删除功能,有一种更简单,更有效的方法:

There's a simpler and more efficient way, using the native shell prefix/suffix removal feature:

temp="${opt%\"}"
temp="${temp#\"}"
echo "$temp"

${opt%\"}将删除后缀"(使用反斜杠转义以防止shell解释).

${opt%\"} will remove the suffix " (escaped with a backslash to prevent shell interpretation).

${temp#\"}将删除前缀"(使用反斜杠转义以防止shell解释).

${temp#\"} will remove the prefix " (escaped with a backslash to prevent shell interpretation).

另一个优点是,只有在有引号的情况下,它才会删除引号.

Another advantage is that it will remove surrounding quotes only if there are surrounding quotes.

顺便说一句,您的解决方案始终会删除第一个和最后一个字符,无论它们是什么(当然,我确定您知道您的数据,但是最好确定要删除的内容).

BTW, your solution always removes the first and last character, whatever they may be (of course, I'm sure you know your data, but it's always better to be sure of what you're removing).

使用sed:

echo "$opt" | sed -e 's/^"//' -e 's/"$//'

(改进的版本,如jfgagne所示,摆脱了回声)

sed -e 's/^"//' -e 's/"$//' <<<"$opt"

因此,它以一无所有替换了前导",也以一无所有替换了尾随".在同一调用中(无需管道传输和启动另一个sed.使用-e您可以进行多个文本处理).

So it replaces a leading " with nothing, and a trailing " with nothing too. In the same invocation (there isn't any need to pipe and start another sed. Using -e you can have multiple text processing).

这篇关于Shell脚本-从变量中删除第一引号和最后引号(“)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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