簡體   English   中英

sed在同一行上匹配模式后插入字符串

[英]sed to insert a string after matching pattern on a same line

某些匹配后,我需要向現有文件插入命令(作為字符串)。 現有的字符串是一個很長的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 regex選項:

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參考捕獲組,然后添加命令文本

您可以使用perl。

用您要添加的內容替換YOUR_COMMAND 假設您的文件位於file.txt

perl -i.bak -pl -e '/^make/ and s/(CC=".*")/$1 YOUR_COMMAND /' file.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM