如何用sed将配对的方括号替换为其他语法? [英] How to replace paired square brackets with other syntax with sed?

查看:357
本文介绍了如何用sed将配对的方括号替换为其他语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用\macro{some text}替换文件中的所有成对方括号,例如[some text]:

I want to replace all pairs of square brackets in a file, e.g., [some text], with \macro{some text}, e.g.:

This is some [text].
This [line] has [some more] text.

它变成:

This is some \macro{text}.
This \macro{line} has \macro{some more} text.

  • 这些对仅出现在单独的行中,而不会跨越多行.
  • 有时一行中可能有不止一对,但它们从未嵌套.
  • 如果仅在一条线上发现了一个括号,而没有一个对,则不应更改.
  • 如何用此代码替换成对的括号?

    How can I replace these pairs of brackets with this code?

    推荐答案

    sed -e 's/\[\([^]]*\)\]/\\macro{\1}/g' file.txt
    

    这将查找一个左括号,任意数量的显式非右括号,然后是一个右括号.该组被括号捕获并插入到替换表达式中.

    This looks for an opening bracket, any number of explicitly non-closing brackets, then a closing bracket. The group is captured by the parens and inserted into the replacement expression.

    这篇关于如何用sed将配对的方括号替换为其他语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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