danny danny - 2 months ago 14
Linux Question

sed to insert a string after matching pattern on a same line

I need to insert a command (as string) to an existing file after a certain match. The existing string is a long make command and I only need to modify it by inserting another string at specific location. I tried using sed but it either adds a new line before/after the matching string or replaces it. I'd like to know if at least it is possible to accomplish what I want with sed or should I be using something else? Could you please provide me with some hints?

Example:

The file contains two make commands and I am only interested in the second one without 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 "$@"

}


Thanks in advance!

Here's the code:
http://hastebin.com/tigatoquje.go

Answer

You could do something like this using Sed:

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

or with sed in-place edit:

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

Without sed regex option:

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

Outputs:

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 "$@"

}

How:

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

-r = regex option

^make(CC=\") = starts with make and set a capture group on CC="

\1your_command_here = \1 reference capture group then add command text