Larry Raab Larry Raab - 1 month ago 6
Linux Question

Efficiently transpose output from tab / new line delimited file in bash in dynamically changing file

EDIT
The number of lines and tab-separate values is also dynamic as it can change. So it might be 1-5 or 1-10 with the same layout but the region will only be listed once.




I have a file with in the following format:(@TSV)

host1 host2 host3
id1 id2 id3
ip1 ip2 ip3
name1 name2 name3
role1 role2 role3
region


I can also format the file like:

host1
host2
host3
id1
id2
id3
ip1
ip2
ip3
name1
name2
name3
role1
role2
role3
region


I would like to write a new file or modify this file inline so the file is in this format: (tsv)

host1 id1 ip1 name1 role1 region
host2 id2 ip2 name2 role2 region
host3 id3 ip3 name3 role3 region


I have tried without success to use awk, sed, for loops... I need some fresh ideas.

Answer

You can use the following awk script:

# translate.awk

NR==1 {
    split($0,hosts)
}
NR==2 {
    split($0,ids)
}
NR==3{
    split($0,ips)
}
NR==4{
    split($0,names)
}
NR==5{
    split($0,roles)
}
NR==6{
    region=$1
}

END{
    OFS="\t"
    for(i in hosts) {
        print hosts[i], ids[i], ips[i], names[i], roles[i], region
    }
}

Call it like this:

awk -f translate.awk input.file