使用sed / awk将一行附加到另一行

时间:2018-07-04 18:30:08

标签: linux bash awk sed

为了简化我想要的,我有这个:

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"

我需要这个(检查组名):

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"

有什么方法可以用sed和/或awk做到这一点?

3 个答案:

答案 0 :(得分:1)

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

输出:

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"

答案 1 :(得分:1)

严格考虑您的实际Input_file与所示示例相同,那么以下内容可能会对您有所帮助。

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

所以在这里我不检查行是否有字符串device,如果您的Input_file在Group之后可能还有许多其他行,那么我们可能必须像@Cyrus的解决方案那样进行检查会。

答案 2 :(得分:0)

使用sed:

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

解释:

/^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

-E选项(对于某些较旧的sed为-r)只是方便;否则,捕获组需要转义,例如\(.*\)