
我有一个包含关键字的文件word1
,word2
下面word2
有一个矩阵
文件.dat
position1: [ 0.0000000, 0.0000000, 0.0000000 ]
word1: 0.0000000
band:
- # 1
word2 :
0.32015595 0.18484212 0.00000000
0.00000000 0.36968424 0.00000000
0.00000000 0.00000000 0.08286072
position2: [ 0.5000000, 0.0000000, 0.0000000 ]
word2: 0.0000000
band:
- # 1
word2 :
0.45015595 0.53484212 0.00000000
0.00000000 0.36968424 0.00000000
0.00000000 0.00000000 0.02476072
.
.
现在我想制作一个格式的文件
position1 word1 word2
position2 word1 word2
.
.
但这里单行的 word2 矩阵为
0.0000000 0.0000000 0.0000000 0.0000000 0.32015595 0.18484212 0.00000000 0.00000000 0.36968424 0.00000000 0.00000000 0.00000000 0.08286072
我已经使用了推荐
awk '/ position | word1 | word2/ {w=w "$2" } END {print w}
但它没有给出预期的结果有人可以帮助我吗?谢谢
答案1
$ awk -F': ' '/position[0-9]+:|word[0-9]+:/ {w=w" "$2 };
/^[0-9. ]+$/ { w=w" "$0 };
/^[[:blank:]]*$/ || eof {if (w) {gsub(/,/,"",w);print w;w=""}}' muthu.txt
[ 0.0000000 0.0000000 0.0000000 ] 0.0000000 0.32015595 0.18484212 0.00000000 0.00000000 0.36968424 0.00000000 0.00000000 0.00000000 0.08286072
[ 0.5000000 0.0000000 0.0000000 ] 0.0000000 0.45015595 0.53484212 0.00000000 0.00000000 0.36968424 0.00000000 0.00000000 0.00000000 0.02476072
或者,使用(IMO)稍微好一点的格式:
$ awk -F': ' '/position[0-9]+:/ {p=$2 };
/word[0-9]+:/ {w=$2};
/^[0-9. ]+$/ {
if (!w2) { w2="[" };
w2=w2" ["$0" ]"
};
/^[[:blank:]]*$/ || eof {
l=p" "w" "w2;
gsub(/ +/," ",l);
gsub(/,/,"",l);
if (l ~ /^[[:blank:]]*$/) {next};
print l" ]";
p=w=w2=""
}' muthu.txt
[ 0.0000000 0.0000000 0.0000000 ] 0.0000000 [ [ 0.32015595 0.18484212 0.00000000 ] [ 0.00000000 0.36968424 0.00000000 ] [ 0.00000000 0.00000000 0.08286072 ] ]
[ 0.5000000 0.0000000 0.0000000 ] 0.0000000 [ [ 0.45015595 0.53484212 0.00000000 ] [ 0.00000000 0.36968424 0.00000000 ] [ 0.00000000 0.00000000 0.02476072 ] ]
这两者都假设输入位于由 1 个或多个空行分隔的段落中。