如何在sed中转义方括号 [英] How to escape square closing bracket in sed

查看:114
本文介绍了如何在sed中转义方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 grep 和 sed 解析遗留的 C 代码,当尝试替换方括号时,发生了一些奇怪的事情.

I'm parsing come legacy C-code using grep and sed and when trying to replace square brackets, something strange happened.

以下用于替换方括号的代码工作正常:

The following code to replace square opening brackets works fine:

$ echo "xyx[xzx]xyx" |sed 的|[\[]||g'

结果:

xyx xzx]xyx

当我现在将 \] 添加到要 sed 的字符串中时,还要替换方括号,它会停止工作:

When I now add \] to the string to sed, to also replace square closing brackets, it stops working:

$ echo "xyx[xzx]xyx" |sed 的|[\[\]]||g'

现在结果:

xyx[xzx]xyx

据我所知,这是转义方括号的正确方法.

As far as I know, this is the proper way to escape square brackets.

我做错了什么?

我在 Ubuntu 14.04 机器上运行它.

I'm running this on a Ubuntu 14.04 machine.

推荐答案

你甚至不需要逃避:

echo "xyx[xzx]xyx" | sed 's|[][]| |g'
xyx xzx xyx

但是请记住,][ 的顺序在这里很重要.

However keep in mind that order of ] then [ is important here.

这篇关于如何在sed中转义方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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