user2274114
user2274114

Reputation: 27

Loop through column then row

I'm sure this has been covered many times but I can't seem to find a good answer...

Here's my file:

$ cat myfile.txt
server1     instance1 instance2 instance3
server2     instance4
server3     instance5 instance6

What I want:

Server: server1, Instance: instance1
Server: server1, Instance: instance2
Server: server1, Instance: instance3
Server: server2, Instance: instance4
Server: server3, Instance: instance5
Server: server3, Instance: instance6

I found a way to do it using an if statement within my loop but surely there's a better way...

Thanks!!

Upvotes: 1

Views: 3039

Answers (2)

Hai Vu
Hai Vu

Reputation: 40763

Bash can handle this task with ease:

#!/bin/bash
# File: format_output.sh
while read server instances
do
    for instance in $instances
    do
        echo "Server: $server, Instance: $instance"
    done
done

To use it:

$ bash format_output.sh < myfile.txt

Upvotes: 4

Ian Kenney
Ian Kenney

Reputation: 6436

If awk is allowed, something like

awk '{for(i=2;i<=NF;i++) print "Server: " $1 ", Instance: " $i }' < myfile.txt

Upvotes: 3

Related Questions