首页 > 解决方案 > 在 Shell 脚本中使用 sed

问题描述

我对脚本和正则表达式真的很陌生,所以我提前道歉。本质上,我正在使用 sed 编写一个 shell 脚本,它将替换我代码中的编译指示。这是一个例子:

#pragma foo=value //一些注释

OUTPUT(value) //一些注释

我试图用底部的表达式替换顶部的表达式,同时仍然保留评论。我不太确定如何将值存储为新表达式的“变量”,因为我看到的所有示例都将某些文本替换为其他文本,而不将任何内容视为变量。我可以得到一些帮助:)吗?

标签: shellscripting

解决方案


首先,一些有用的链接供进一步学习 -

在此处了解正则表达式

在这里测试和试错你的正则表达式


现在关于问题本身,sed可以做的不仅仅是替换文本,但是当涉及到替换时,语法是sed -E 's/regex/replacement/flags'.

正如您可能已经看到的,正则表达式没有“变量”的概念,而是有所谓的“捕获组”。

让我们从一个简单的正则表达式开始找到您的确切示例:#pragma foo=value //some comment

要处理任何“值”,我们可以将“值”替换为\w+,这意味着任意数量的字母或数字:#pragma foo=\w+ //some comment

现在难题的最后一块是能够在替换中使用值本身。因此,首先将一部分正则表达式放在一个组中,您只需用括号括起来:#pragma foo=(\w+) //some comment

现在我们可以使用\1引用正则表达式中的第一个捕获组,因此替换字符串将如下所示:OUTPUT(\1) //some comment

Now to put it all together in a sed command, I don't think you want any flags here, but you might notice that the sed syntax includes slashes, but so does our regex and replacement. So we can either escape them with a backslash, but actually sed doesn't care if we use slashes or anything else to separate the arguments, so we can instead use for example sed 's|regex|replacement|flags'.

The result is sed -E 's|#pragma foo=(\w+) //some comment|OUTPUT(\1) //some comment|'

The -E flag tells sed we're using regex features instead of regular text, without it our regex won't actually work.


There might be better ways to write your regex exactly like you want, but I think this should get you started.

Lastly, you may want to check out awk, another really powerful shell command that can edit text, you may like it better.


推荐阅读