我确信这已被多次覆盖,但我似乎无法找到一个好的答案......
这是我的档案:
$ 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 :(得分: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
答案 1 :(得分:3)
如果允许使用awk,例如
awk '{for(i=2;i<=NF;i++) print "Server: " $1 ", Instance: " $i }' < myfile.txt