我有一个文本文件,materials.txt
其中包含大量类似于此的材料定义:
*FILESTART
line_a
line_b
line_c
*MAT_PLASTIC
1 property1 property2 property3
property4 property5 property6 property7
*MAT_STEEL
2 property1 property2 property3
property4 property5 property6 property7
*MAT_WOOD
3 property1 property2 property3
property4 property5 property6 property7
*MAT_ALUMINUM
4 property1 property2 property3
property4 property5 property6 property7
*MAT_RUBBER
5 property1 property2 property3
property4 property5 property6 property7
*MAT_GOLD
6 property1 property2 property3
property4 property5 property6 property7
*SOMETHING_ELSE
line_x
line_y
line_z
*END
每个部分都以一个标题开始,以星号 (*) 开头,以下一个星号结束。
我想仅打印含有金属(即 *MAT_STEEL、*MAT_ALUMINUM 和 *MAT_GOLD)的部分,并打印每种材料的所有属性。所需的输出如下:
2 property1 property2 property3
property4 property5 property6 property7
4 property1 property2 property3
property4 property5 property6 property7
6 property1 property2 property3
property4 property5 property6 property7
我可以打印一材料,例如*MAT_STEEL,如下所示:
awk '/^\*/ { f=0 } /^\*MAT_STEEL$/ { f=1 ; next } f' materials.txt
结果:
2 property1 property2 property3
property4 property5 property6 property7
由于我的真实文件中的金属列表实际上要长得多,因此我想创建一个列表并像这样循环遍历它:
#!/bin/bash
METALS="MAT_STEEL MAT_ALUMINUM MAT_GOLD MAT_SOMETHING1 MAT_SOMETHING2 MAT_SOMETHING3"
for M in $METALS ; do
awk -v mtrl="$M" '/^\*/ { f=0 } "/^\*" mtrl "$/" { f=1; next } f' materials.txt
done
无论我如何使用“mtrl”变量,都无法获得正确的输出。有人可以帮忙吗?
答案1
只需一次 awk 调用:
awk '
BEGIN {
metal["*MAT_STEEL"] = 1
metal["*MAT_ALUMINUM"] = 1
metal["*MAT_GOLD"] = 1
metal["*MAT_SOMETHING1"] = 1
metal["*MAT_SOMETHING2"] = 1
metal["*MAT_SOMETHING3"] = 1
}
$1 ~ /^[*]/ {p = 0}
$1 in metal {p = 1; next}
p
' materials.txt
2 property1 property2 property3
property4 property5 property6 property7
4 property1 property2 property3
property4 property5 property6 property7
6 property1 property2 property3
property4 property5 property6 property7