我有一个这样的文件
field01 field02 field03 field04 definition: field05; measure: field06; weight: field07;
field11 field12 field13 field14 definition: field15; measure: field16;
field21 field22 field33 definition: field25; weight: field27;
field31 field32 field03 field34 definition: field35; measure: field36; wight: field47;
所需的输出是第二个字段和“定义”之后的字段:
field02 field05
field12 field15
field22 field25
field32 field35
分隔符包括“ ”、“定义:”和“;”
我做的最多的是
awk -F'definition:' '{print $2}' file |awk 'split($1, a, ");") {print substr(a[1],-5)}'
它给了我:
field05;
field15;
field25;
field35;
但这不是我想要的。 field05、field15 和 field35 可以具有不同的长度
答案1
试试这个 awk:
awk '
{
split($0,temp,"definition: ") #Get everything after "definition: " in temp[2]
split(temp[2],final,";") #Get everything between "definition :" and ";" in final[1]
print $2,final[1]
}'
一件内衬,根据要求:
awk '{split($0,t,"definition: ");split(t[2],f,";");print $2,f[1]}'
答案2
有点hacky的建议:
awk -F'[:;]' '{ print $2,$1 }' file | awk -F' ' '{ print $2, $1 }'
输出
field01 field05
field11 field15
field21 field25
field31 field35
答案3
演出迟到了,但另一个awk
解决方案只是为了好玩
awk -F'[ ;]' '{f=3; while ($f!~"defin") f++; print $2, $(f+1)}' file1
答案4
尝试使用下面的命令,效果很好
awk '{for (i=1;i<=NF;i++){if($i ~ /definition:/){gsub(";","",$(i+1));print $2,$(i+1)}}}' filename
输出
field02 field05
field12 field15
field22 field25
field32 field35