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

查看:103
本文介绍了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 脚本 - 从变量中删除第一个和最后一个引号 (&quot;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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