bash行在脚本中迭代

时间:2015-04-28 13:12:31

标签: bash text iteration

我在文本文件中有以下数据

INSTANCES machine1    
Name    Berlin
Role    NA
INSTANCES  machine2   
Name    London
Role    NA
INSTANCES machine3       
Role    parser
Name    Dublin
INSTANCES machine4       
Name    Madrid
INSTANCES machine5
Role    parser
Name    Lisbon

我需要创建以下输出。我怎么能这样做

machine1    Berlin    NA
machine2    London    NA
machine3    Dublin    parser
machine4    Madrid    NONE
machine5    Lisbon    parser

1 个答案:

答案 0 :(得分:0)

这应该这样做:

#!/bin/bash
count=0
while read -r line; do
arr=($line)
if [[ $line == *INSTANCES* ]]; then
[[ $count != 0 ]] && new+="\n"${arr[1]} || new+=${arr[1]}
else
new+=" ${arr[1]}"
fi
((count++))
done <file
new+="\n"
printf "$new"

文件是文本文件名