【问题标题】:Conditional matching with multiple fields comparison in different files using AWK使用 AWK 在不同文件中进行多字段比较的条件匹配
【发布时间】:2022-01-09 20:06:36
【问题描述】:

关于如何匹配 2 个单独文件中的 2 个字段/列,包括记录的条件匹配(状态 Employee.txt 中的“X”和可用性 = Car.txt 中的“Y”),我再次需要您的帮助。 Employee.txt($1 - 员工编号,$2 - 运动)。 Car.txt($4 - 员工编号,$2 - 运动)。以下是我想要实现的目标:

Employee1.txt (last column is the **status**)
1|canoeing|Sam|Smith|Seatle|X
2|jogging|Barry|Jones|Seatle|
3|football|Garry|Brown|Houston|
4|jogging|George|Bla|LA|X
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

Car1.txt (last column is **availability**)
100|football|blue|5|Y
110|tennis|green|9|N
120|hockey|yellow|8|N
130|football|yellow|6|N
140|jogging|red|2|Y
150|canoeing|white|0|
    
awk -F"|" '
NR==FNR {
  if ($NF == "Y")
     car[$4,$2]
     next
}
{
    print > ($NF != "X" && ($1,$2) in car ? "match.txt" : "no_match.txt")
}' Car.txt Employee.txt

no_match.txt is the same as Employee.txt. Zero records in match.txt.

Desire output:
match.txt
2|jogging|Barry|Jones|Seatle|
5|basketball|Celine|Wood|Atlanta|

no_match.txt
3|football|Garry|Brown|Houston|
6|tennis|Jody|Ford|Chicago|

非常感谢, 乔治

【问题讨论】:

  • 请将该单片灰色文本块分隔为输入、输出和代码文件的单独块,并在中间插入说明性文本。
  • 您应该为此类任务安装一些关系数据库。 (例如 Access、Sqlite、MySql)。
  • 我已经有了,但只是想在进行大规模记录更新之前收集数据。谢谢

标签: awk aix


【解决方案1】:

注意:根据您的要求,

5|basketball|Celine|Wood|Atlanta|

不应在 match.txt 中,因为两个文件中的运动项目不同(足球与篮球

如果你想在“no_match.txt”中输入status "X"

$  awk -F"|" '                
NR==FNR { if ($NF == "Y") car[$4 FS $2]=1; next }
{ print > ( ($NF!="X" && ($1 FS $2) in car) ? "match.txt" : "no_match.txt") }' c.txt e.txt

结果:

kent$  head match.txt no_match.txt
==> match.txt <==
2|jogging|Barry|Jones|Seatle|

==> no_match.txt <==
1|canoeing|Sam|Smith|Seatle|X
2|jogging|Barry|Jones|Seatle|
3|football|Garry|Brown|Houston|
4|jogging|George|Bla|LA|X
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

如果要排除“X”条目:

kent$  awk -F"|" '                
NR==FNR { if ($NF == "Y") car[$4 FS $2]=1; next }
$NF!="X"{ print > (($1 FS $2) in car? "match.txt" : "no_match.txt") }' c.txt e.txt 

结果:

kent$  head match.txt no_match.txt
==> match.txt <==
2|jogging|Barry|Jones|Seatle|

==> no_match.txt <==
3|football|Garry|Brown|Houston|
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

【讨论】:

  • awk -F"|" ' NR==FNR { if ($NF == "Y") car[$4 FS $2]=1; next } { print > ( ( ($NF != "X") && ($1 FS $2) in car) ? "match.txt" : "no_match.txt") } 得到相同的输出。您的最后一条打印语句因语法错误而无效。感谢您帮助肯特!
猜你喜欢
  • 2022-01-08
  • 2012-10-18
  • 1970-01-01
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2017-07-03
  • 1970-01-01
相关资源
最近更新 更多