user1684072
user1684072

Reputation: 169

Find and concatenate lines using sed

I have a struct blocks within a long c file

struct node {
   int val;
   struct node *next;
};

How do I use the sed function to find this struct block and convert it into one line. So it looks like this:

struct node {   int val;   struct node *next;};

Thanks in advance


My input is this:

struct node {
   int val;
   struct node *next;
};

typedef struct {
   int numer;
   int denom;
} Rational;

int main()
{
struct node head;
Rational half, *newf = malloc(sizeof(Rational));

head = (struct node){ 5, NULL };
half = (Rational){ 1, 2 };
*newf = (Rational){ 2, 3 };
}

My output is :

struct node { int val; struct node *next;};

typedef struct { int numer; int denom;} Rational;int main(){struct node head;Rational  half, *newf = malloc(sizeof(Rational));head = (struct node){ 5, NULL };
half = (Rational){ 1, 2 };
*newf = (Rational){ 2, 3 };
}

I only want the struct node: struct node { int val; struct node *next;};
and the typedef struct: typedef struct { int numer; int denom;} Rational; to be in one line. However int main() is being appended to the end of Rational;

I want the stuff in the main function to remain as it is.

Upvotes: 3

Views: 425

Answers (1)

perreal
perreal

Reputation: 98078

With sed:

sed '/struct[^(){]*{/{:l N;s/\n//;/}[^}]*;/!t l;s/  */ /g}' input.c

When sed sees a struct definition (/struct[^{]*{/), it will read lines until a }; is seen on a line (:l N;s/\n//;/[}];/!t l;) while also removing newlines. When it matches }; it removes extra spaces (;s/ */ /g).

Upvotes: 3

Related Questions