Have data like
start {data}
target {ABC}
start {data2}
target {DEF}
target {GHI}
start {data3}
target {JKL}
....
I wish to move the {data} or {data2} which are after the keyword ‘start’ to their next lines i.e.
start {data}
target {data ABC}
start {data2}
target {data2 DEF}
target {data2 GHI}
start {data3}
target {data3 JKL}
....
I tried
sed '/^[[:space:]]*start*/{ N;s/[[:space:]]*target / /}'
But this is not giving the desired output.
1
Using sed
$ sed -E '/start/{p;s/^[0-9]+.start[^{]*{([^}]*).*/1 /;h;d};/target/{G;s/({)([^}]*})n(.*)/132/}' input_file
1.start {data}
2.target {data ABC}
3.start {data2}
4.target {data2 DEF}
5.target {data2 GHI}
6.start {data3}
7.target {data3 JKL}
..
..
2
Your attempt would simply replace target
with nothing. It contains no code to capture the actual value between the braces. But frankly, I would avoid sed
for anything beyond single-line search and replace.
Here is a simple Awk solution.
awk '/^[[:space:]]*start / { split($0, tag, "[{}]") }
!/^[[:space:]]*start / && tag[2] { sub(/{/, "{" tag[2] " ") }
1'
If the regex matches, split the line into the array tag
on curly braces. Thus, the value in tag[2]
is the value between the curlies.
Otherwise, replace the opening curly to add the stored value of tag[2]
from the previous matching line.
The 1
is a shorthand to print all lines unconditionally.
Demo: https://ideone.com/ZRJACS