2013-04-24 48 views
1

我敢肯定,這已經覆蓋了很多次,但我似乎無法找到一個很好的答案...遍歷柱然後劃

這是我的文件:

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

我想要什麼:

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

我發現了一個辦法做到這一點使用我的循環內的if語句,但肯定有一個更好的辦法...

謝謝小號!

+0

它應該是在bash,只用sed和awk?在python中這將會變得更加微不足道,現在每個服務器都帶着它。 – fotanus 2013-04-24 00:53:17

回答

4

Bash可以輕鬆地完成這一任務:

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

要使用它:

$ bash format_output.sh < myfile.txt 
3

如果AWK是允許的,像

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