编辑问题以尝试使事情更清楚
我有一个如下所示的文件:
BEGIN
Block name : Block1
Var names : var1 var2 var3
var1 32.7
var2 12.2
var3 65.4
END
BEGIN
Block name : Block43
Var names : bar55 foo3
bar55 654.555
foo3 23.4
END
BEGIN
Block name : Block66
Var names : bar2
bar2 33.0987
END
最终输出应该是:
Block1 has a var named var1 and its value is 32.7
Block1 has a var named var2 and its value is 12.2
Block1 has a var named var3 and its value is 65.4
Block43 has a var named bar55 and its value is 654.555
Block43 has a var named foo3 and its value is 23.4
Block66 has a var named var1 and its value is 33.0987
我不知道块的大小或它有多少个变量。
我确实知道每个块都被 BEGIN 和 END 行包围。
有没有办法将文件解析为单独的块并循环遍历它们?
内容如下:
for block in file; do
block_name=$(echo $block | grep 'Block' | cut -d ":" -f2)
vars=$(echo $block | grep 'Var' | cut -d ":" -f2)
for var in $vars;do
var_value=$(echo $block | grep '^$var')
echo "$block_name has a var named $var and its value is $var_value"
done
done
对我的问题最接近的答案是使用 sed 或 awk 来获取块的第一个实例,然后退出。
我希望从 BEGIN 和 END 包围的每个块中获取信息。
感谢您的帮助。
答案1
$ cat tst.awk
/^Block name/ { name = $NF }
/END/ {
for (var in var2val) {
printf "%s has a var named %s and its value is %s\n", name, var, var2val[var]
}
delete var2val
}
NF==2 { var2val[$1] = $2 }
$ awk -f tst.awk file
Block1 has a var named var1 and its value is 32.7
Block1 has a var named var2 and its value is 12.2
Block1 has a var named var3 and its value is 65.4
Block43 has a var named foo3 and its value is 23.4
Block43 has a var named bar55 and its value is 654.555
Block66 has a var named bar2 and its value is 33.0987
答案2
这是一种方法:
$ awk '/^Block/{block=$1}
/foo/{
printf "The value of foo in %s is : %s\n",block,$2
}' file
The value of foo in Block1 is : 5423
The value of foo in Block2 is : 6435907
The value of foo in Block3 is : 353321111
The value of foo in Block4 is : 9876543210
或者,如果您可以有多行以 开头,Block
并且您只想要紧随 后面的一行BEGIN
,则可以使用:
awk '/BEGIN/{a=1}
/END/{a=0}
/^Block/ && a{
block=$1;
a=0
}
/foo/{
printf "The value of foo in %s is : %s\n",block,$2
}' file