删除 case 子句: sed 正则表达式中的 bash 扩展: X='a\.b' ; Y=';;' sed -n '/${X}/,/${Y}/d'
我正在尝试从 bash 脚本中删除 case 子句。该子句会有所不同,但始终将反斜杠作为大小写匹配字符串的一部分。
我正在尝试 sed,但可以在 bash 脚本中使用 awk 或 perl 单行代码。
编辑的目标很简单,类似于:
$cat t.sh
case N in
a\.b);
#[..etc., varies]
;;
esac
我与转义反斜杠、分号或两者的变量扩展发生冲突。如果我“评估”,我会去掉反斜杠转义符。如果我不这样做,分号就会追上我。所以我尝试了 sed 内的子 shell 扩展。正如我所写的那样,这让翻译人员犯了错误。更多转义分号似乎没有帮助。
X='a\.b' ; Y=';;'
sed -i '/$(echo ${X} | sed -n 's/\\/\\\\/g')/,/$(echo ${Y} | sed -n s/\;/\\;/g')/d t.sh
还有这个:
perl -i.bak -ne 'print unless /${X}/ .. /{$Y}/' t.sh # which empties t.sh
和
eval perl -i.bak -ne \'print unless /${X}/ .. /{$Y}/' t.sh # which does nothing
I'm trying to remove a case clause from a bash script. The clause will vary, but will always have backslashes as part of the case-match string.
I was trying sed but could use awk or a perl one-liner within the bash script.
The target of the edit is straightforward, resembles:
$cat t.sh
case N in
a\.b);
#[..etc., varies]
;;
esac
I am running afoul of the variable expansion escaping backslashes, semicolons or both. If I 'eval' I strip my backslash escapes. If I don't, the semi-colons catch me up. So I tried subshell expansion within the sed. This fouls the interpreter as I've written it. More escaping the semi-colons doesn't seem to help.
X='a\.b' ; Y=';;'
sed -i '/$(echo ${X} | sed -n 's/\\/\\\\/g')/,/$(echo ${Y} | sed -n s/\;/\\;/g')/d t.sh
And this:
perl -i.bak -ne 'print unless /${X}/ .. /{$Y}/' t.sh # which empties t.sh
and
eval perl -i.bak -ne \'print unless /${X}/ .. /{$Y}/' t.sh # which does nothing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Bash 的
printf
具有引用功能,可以提供帮助:或者您还可以使用
printf
变量赋值功能:请注意在
sed
命令参数。单引号将防止变量扩展和命令替换。但是,当不使用这些时,通常最好使用单引号。Bash's
printf
has a quoting feature that will help:or you can additionally use the
printf
variable assignment feature:Note the use of double quotes around the
sed
command argument. Single quotes will prevent the expansion of variables and command substitution. When those aren't being used, though, it's usually best to use single quotes.这是用 shell 引用玩游戏,但效果很好。 :)
This is playing games with shell quoting, but it works pretty well. :)