Adrián Acosta
Adrián Acosta

Reputation: 29

Using sed/awk to append one line to another

To simplify what I want, I have this:

Group name="Group1"
Device name="G1_Device1" host="G1_host1"
Device name="G2_Device2" host="G1_host2"
Group name="Group2"
Device name="G2_Device1" host="G2_host1"
Group name="Group3"
Device name="G3_Device1" host="G3_Host1"
Device name="G3_Device2" host="G3_host2"
Device name="G3_Device3" host="G3_host3"
Device name="G3_Device4" host="G3_host4"

And I need this (check the group name):

Group name="Group1" Device name="G1_Device1" host="G1_host1"
Group name="Group1" Device name="G2_Device2" host="G1_host2"
Group name="Group2" Device name="G2_Device1" host="G2_host1"
Group name="Group3" Device name="G3_Device1" host="G3_Host1"
Group name="Group3" Device name="G3_Device2" host="G3_host2"
Group name="Group3" Device name="G3_Device3" host="G3_host3"
Group name="Group3" Device name="G3_Device4" host="G3_host4"

Is there any way to do that with sed and/or awk?

Upvotes: 0

Views: 208

Answers (3)

Benjamin W.
Benjamin W.

Reputation: 52536

With sed:

sed -E '/^Group/{h;d};G;s/(.*)\n(.*)/\2 \1/' infile

Explained:

/^Group/ {              # If the line starts with "Group"...
    h                   # copy pattern space to hold space
    d                   # Delete pattern space, start new cycle
}
G                       # Append hold space to pattern space (inserts newline)
s/(.*)\n(.*)/\2 \1/     # Swap two lines in pattern space

The -E option (-r for some older seds) is just convenience; otherwise, the capture groups need escaping, as in \(.*\).

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133770

Strictly considering that your actual Input_file is same as shown samples then following may help you here.

awk '/^Group name/{value=$0;next} {print value,$0}' Input_file

So here I am not doing the check if a line is having string device or not, if your Input_file may have many other lines after Group then we may have to put check like @Cyrus's solution does.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88999

awk '$1=="Group"{save=$0}; $1=="Device"{print save,$0}' file

Output:

Group name="Group1" Device name="G1_Device1" host="G1_host1"
Group name="Group1" Device name="G2_Device2" host="G1_host2"
Group name="Group2" Device name="G2_Device1" host="G2_host1"
Group name="Group3" Device name="G3_Device1" host="G3_Host1"
Group name="Group3" Device name="G3_Device2" host="G3_host2"
Group name="Group3" Device name="G3_Device3" host="G3_host3"
Group name="Group3" Device name="G3_Device4" host="G3_host4"

Upvotes: 1

Related Questions