shell - 在 Shell 脚本中使用 sed
问题描述
我对脚本和正则表达式真的很陌生,所以我提前道歉。本质上,我正在使用 sed 编写一个 shell 脚本,它将替换我代码中的编译指示。这是一个例子:
#pragma foo=value //一些注释
到
OUTPUT(value) //一些注释
我试图用底部的表达式替换顶部的表达式,同时仍然保留评论。我不太确定如何将值存储为新表达式的“变量”,因为我看到的所有示例都将某些文本替换为其他文本,而不将任何内容视为变量。我可以得到一些帮助:)吗?
解决方案
首先,一些有用的链接供进一步学习 -
现在关于问题本身,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.
推荐阅读
- jsonpath - 根值的 JSON 路径字符串评估
- spring - 带有帖子的 Spring WebMvcTest 返回 403
- angular - Ionic 3 Firebase Angular 本地存储
- css - Badge-pill 和 h2 水平对齐
- vue-resource - Vue-Resource:如何从 JSON 获取和显示多个数组
- android - 无法为飞溅的 android 播放此视频
- php - PHP 数组:需要的输出
- javascript - Javascript - 将对象指向鼠标
- python - 如何通过变量名导入模块以及如何命名所述模块
- visual-studio - Visual Studio,将文件复制到项目目录问题