简体   繁体   中英

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?

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"

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.

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 \\(.*\\) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM