Detecting and concatenating a multi-line structure using sed Detecting and concatenating a multi-line structure using sed unix unix

Detecting and concatenating a multi-line structure using sed


I'd do something in the line of this:

$ sed -n '/struct/,/};/p' input | sed -e ':a;N;$!ba;s/\n//g'struct apple {    int type, color;    Apple app;};

The construct /foo/,/bar/ selects all lines (inclusive) between patterns.

The N command appends a newline and the next line to current pattern space. Then the famous s/// command gets executed which replaces the newline character with nothing, i.e. join of lines.


there may be better way to solve this problem, e.g. awk maybe with tr. However since you mentioned that this is homework, and must be done by sed, I wrote the below commands (one liner :D ). note, there are two "sed" command. hope it could be accepted.

command to solve the problem:

sed -rn '/^struct/{x;s/.*/#/g;x;p;n};     /\};/ {x;/#/{s/#//;x;p;n}};    x; /#/{x;p}' yourFile | sed -r ':a;N; s/\n//g;s/\};/&\n/g; ba;' 

now let's do a test, I created a file named t.c. see the content:

kent$  cat t.cstruct apple1 {    int type, color;    Apple app;};// ... more code// ... more code// ... more code// ... more codefunction abc(para){ foo; bar; return ;}struct apple2 {    int type, color;    Apple app;};// ... more code// ... more code// ... more code struct apple3 {    int type, color;    Apple app;};// ... more code

now play my sed commands with the t.c baby:

kent$  sed -rn '/^struct/{x;s/.*/#/g;x;p;n};         /\};/ {x;/#/{s/#//;x;p;n}};        x; /#/{x;p}' t.c | sed -r ':a;N; s/\n//g;s/\};/&\n/g; ba;' struct apple1 {    int type, color;    Apple app;};struct apple2 {    int type, color;    Apple app;};struct apple3 {    int type, color;    Apple app;};