awk在找到图案时加入或合并线 [英] awk to Join or merge lines on finding a pattern

查看:51
本文介绍了awk在找到图案时加入或合并线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件中有一些数据需要排序(也许使用awk),如果可能的话,希望能为您提供一些帮助

I have some data in a file i need to sort (maybe using awk) and would appreciate some help if possible

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

Here is a small sample of the file..

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步,我想把线放在一起

STEP 1 I would like bring lines together

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步,我想过滤出只显示数字4的行

STEP 2 i would like to filter out the lines with just the number FOUR present

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

第3步,我只想显示以下内容

STEP 3 i want to just display the following

7996012132 FOUR

7996020216 FOUR

有什么想法吗?预先感谢!

Any ideas? Thanks in advance!

推荐答案

这是我的解决方案:

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

说明:

# 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 }

然后,您可以基于包含'FOUR'且以作为字段分隔符的行来解析所需的数字:

Then you can parse out the number you want based on lines that contain 'FOUR' with , as the field separator:

awk -F, '/FOUR/ {print $3" FOUR"}'

这篇关于awk在找到图案时加入或合并线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆