regex - sed 在同一行匹配模式后插入一个字符串

标签 regex linux bash sed

我需要在特定匹配后向现有文件插入命令(作为字符串)。现有的字符串是一个很长的 make 命令,我只需要通过在特定位置插入另一个字符串来修改它。我尝试使用 sed 但它要么在匹配字符串之前/之后添加一个新行,要么替换它。我想知道是否至少有可能用 sed 完成我想要的,或者我应该使用其他东西吗?你能给我一些提示吗?

例子:

该文件包含两个 make 命令,我只对第二个没有 bbnote 的命令感兴趣。

oe_runmake_call() {
        bbnote make -j 8 CROSS_COMPILE=arm-poky-linux-gnueabi- CC="arm-poky-linux-gnueabi-gcc" "$@"
        make -j 8 CROSS_COMPILE=arm-poky-linux-gnueabi- CC="my_command_here arm-poky-linux-gnueabi-gcc"  --sysroot=/some/path "$@"

}

提前致谢!

代码如下: http://hastebin.com/tigatoquje.go

最佳答案

你可以使用 Sed 做这样的事情:

sed -r 's:(^\s+make.+ CC=\"):\1your_command_here :g' file.log >outfile.log

或使用 sed 就地编辑:

sed -ir 's:(^\s+make.+ CC=\"):\1your_command_here :g' file.log

没有 sed 正则表达式选项:

sed 's:\(^\s\+make.\+ CC=\"\):\1your_command_here :g' file.log > outfile.log

输出:

oe_runmake_call() {
        bbnote make -j 8 CROSS_COMPILE=arm-poky-linux-gnueabi- CC="arm-poky-linux-gnueabi-gcc" "$@"
        make -j 8 CROSS_COMPILE=arm-poky-linux-gnueabi- CC="your_command_here arm-poky-linux-gnueabi-gcc"  --sysroot=/some/path "$@"

}

如何:

sed -r 's:(^\s+make.+ CC=\"):\1your_command_here :g'

-r = 正则表达式选项

^make(CC=\") = 从 make 开始并在 CC="

上设置捕获组

\1your_command_here = \1 引用捕获组然后添加命令文本

关于regex - sed 在同一行匹配模式后插入一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874914/

相关文章:

python - 如何从 Bash 脚本在后台运行 Python 脚本?

bash - 防止 bash 脚本中的通配符扩展

javascript - 使用正则表达式选择 "#"符号后的所有文本

Python:正则表达式 re.compile(r'^[-\w]+$') 如何搜索?或者,正则表达式在这种情况下如何工作?

用于匹配 JSON 子字符串的某些部分的 Java 正则表达式

linux - 如何使用 SPARC 求解器的输出作为 python 文件的输入?

c - 使用pmap分析进程的内存映射。 [堆栈]

linux - 在亚马逊云服务器上设置 FTP

linux - shell 脚本: Redirect output of program to changing files

用于匹配包括特殊字符在内的整个单词的Javascript正则表达式