我需要在特定匹配后向现有文件插入命令(作为字符串)。现有的字符串是一个很长的 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 "$@"
}
提前致谢!
最佳答案
你可以使用 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/