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 语句的方法,但肯定有更好的方法......

谢谢!!

4

2 回答 2

4

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
于 2013-04-24T01:21:32.123 回答
3

如果允许 awk,则类似于

awk '{for(i=2;i<=NF;i++) print "Server: " $1 ", Instance: " $i }' < myfile.txt
于 2013-04-24T00:59:22.843 回答