awk在寻找模式时加入或合并线条

时间:2016-09-23 20:00:36

标签: awk sed

我在需要排序的文件中有一些数据(可能使用awk)并且如果可能的话会感谢一些帮助

以下是该文件的一小部分示例..

DEFAULT,number,7996012132,,test,1,SP_A,SIX,,,

,,,,FOUR,,,

,,,,NINE,,,

,,,,TWO,,,

DEFAULT,number,7996020217,,test,1,SP_B,,,,,

DEFAULT,number,7996020218,,test,1,SP_B,,,,,

DEFAULT,number,7996020218,,test,1,SP_A,THREE,,,

,,,,TWO,,,

,,,,NINE,,,

,,,,THREE,,,

DEFAULT,number,7996020215,,test,1,SP_B,,,,,

DEFAULT,number,7996020216,,test,1,SP_A,SIX,,,

,,,,SEVEN,,,

,,,,EIGHT,,,

,,,,FOUR,,,

第1步我想把线放在一起

DEFAULT,number,7996012132,,test,1,SP_A,SIX,,,,,,,FOUR,,,,,,,NINE,,,,,,,TWO,,,
DEFAULT,number,7996020217,,test,1,SP_B,,,,,
DEFAULT,number,7996020218,,test,1,SP_B,,,,,
DEFAULT,number,7996020218,,test,1,SP_A,THREE,,,,,,,TWO,,,,,,,NINE,,,,,,,THREE,,,
DEFAULT,number,7996020215,,test,1,SP_B,,,,,
DEFAULT,number,7996020216,,test,1,SP_A,SIX,,,,,,,SEVEN,,,,,,,EIGHT,,,,,,,FOUR,,,

第2步我想过滤出只有FOUR数字的行

DEFAULT,number,7996012132,,test,1,SP_A,,SIX,,,,,,,FOUR,,,,,,,NINE,,,,,,,TWO,,,
DEFAULT,number,7996020216,,test,1,SP_A,,SIX,,,,,,,SEVEN,,,,,,,EIGHT,,,,,,,FOUR,,,

第3步我想显示以下内容

7996012132 FOUR

7996020216 FOUR

有什么想法吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

这是我的解决方案:

>>> numpy.log(3)
1.0986122886681098
>>> type(_)  # Not a Python float!
<type 'numpy.float64'>

解释:

awk 'BEGIN {line=""} /DEFAULT/ {print line; line=$0} !/DEFAULT/ {line = line""$0} END {print line}' data.txt | awk -F, '/FOUR/ {print $3" FOUR"}'

然后,您可以根据包含&#39;四个&#39;的行来解析您想要的数字。使用# Initialize line variable to blank BEGIN { line="" } # If the line contains DEFAULT, print what we have and start a new aggregation /DEFAULT/ { print line; line=$0 } # If the line does not contain DEFAULT, add this line to the variable !/DEFAULT/ { line = line""$0 } # At the end, print whatever we have END { print line } 作为字段分隔符:

,

答案 1 :(得分:0)

第一部分:

/^$/ {next}                                     # this removes the empty records in your data
{
    printf "%s", (NR > 1 && /^DEF/ ?ORS:"") $1  # print
}

测试它:

$ awk -f foo.awk foo.txt
DEFAULT,number,7996012132,,test,1,SP_A,SIX,,,,,,,FOUR,,,,,,,NINE,,,,,,,TWO,,,
DEFAULT,number,7996020217,,test,1,SP_B,,,,,
DEFAULT,number,7996020218,,test,1,SP_B,,,,,
DEFAULT,number,7996020218,,test,1,SP_A,THREE,,,,,,,TWO,,,,,,,NINE,,,,,,,THREE,,,
DEFAULT,number,7996020215,,test,1,SP_B,,,,,
DEFAULT,number,7996020216,,test,1,SP_A,SIX,,,,,,,SEVEN,,,,,,,EIGHT,,,,,,,FOUR,,,

第二部分:

/^$/ {next} 
/^DEF/ {
    if(NR>1&&foo~/FOUR/)print foo;foo=""
} 
{
    foo=foo $1
} 
END{if(foo~/FOUR/) print foo}