在两个文件中匹配valueS并在选定的列中替换

时间:2019-04-20 09:58:26

标签: awk

如果file1中第1,2和5列的值与file2中第1,2和9列匹配。

然后使用文件1的第3,4列的信息替换文件2的第1,2列中的值

在输出文件中为替换的行添加字符R,为未替换的行添加字符O。还要从file1中添加第1列和第2列以匹配记录。

file1

37267.00  37181.00  37267.00  37181.00  2605  
37269.00  37181.00  37267.00  37184.00  2605  
37271.00  37181.00  37271.00  37181.00  2603  
36829.00  37185.00  36820.00  37184.00  2605  
36831.00  37187.00  36831.00  37185.00  2605  
36833.00  37189.00  36833.00  37189.00  2605  
36835.00  37191.00  36831.00  37194.00  2606

file2

37267.00  37181.00  8424   36840.00  37260.00  37146.00  37612.00  36  2605
37269.00  37181.00  8424   36840.00  37260.00  37146.00  37612.00  36  2605
37271.00  37181.00  8424   36840.00  37260.00  37146.00  37612.00  36  2603
36829.00  37185.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605
36831.00  37187.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605
36833.00  37189.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605
36835.00  37191.00  8640   36840.00  37260.00  37146.00  37624.00  36  2606

output desired

37267.00  37181.00  8424   36840.00  37260.00  37146.00  37612.00  36  2605  O 37267.00  37181.00
37267.00  37184.00  8424   36840.00  37260.00  37146.00  37612.00  36  2605  R 37269.00  37181.00
37271.00  37181.00  8424   36840.00  37260.00  37146.00  37612.00  36  2603  O 37271.00  37181.00
36820.00  37184.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605  R 36829.00  37185.00
36831.00  37185.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605  R 36831.00  37187.00
36833.00  37189.00  8640   36840.00  37260.00  37146.00  37624.00  36  2605  O 36833.00  37189.00
36831.00  37194.00  8640   36840.00  37260.00  37146.00  37624.00  36  2606  R 36835.00  37191.00

我尝试过

awk '
FNR==NR{
  a[$1 $2 $5]=$3 $4
  b[$3 $4]=$3
  c[$3 $4]=$4
  next
}
($1 in a){
  $1=b[$1]
  $2=c[$1]
  $1=a[$1]
  found=1
}
{
  $0=found==1?$0",R":$0",O"
  sub(/^...../,"&,")
  $1=$1
  found=""
}
1
' FS=" " file1 FS=" " OFS=" " file2

预先感谢

2 个答案:

答案 0 :(得分:2)

编辑: :由于OP更改了Input_file的示例数据,因此现在添加此解决方案。

{ this.props.checkins.map((checkin, key) => {
  return(
    <div key={key}>
      <p>ID{checkin.placeid}, Address:{checkin.username}</p>
    </div>
  )
})}


似乎您所显示的预期输出与您所说明的条件不匹配,如果是这种情况,请尝试以下方法(仅使用所显示的示例进行测试)。

awk '
FNR==NR{
  a[$3,$4,$5]=$3
  b[$3,$4,$5]=$4
  next
}
{
  val=$1 SUBSEP $2 SUBSEP $9
  val_last=$1 OFS $2
}
(val in a){
  $2=b[val]
  $1=a[val]
  print $0,"R",val_last
  next
}
{
  print $0,"O",val_last
}'  Input_file1  Input_file2  | column -t

为什么OP的代码不起作用: :因为一旦awk ' FNR==NR{ a[$1,$2,$5]=$3 b[$1,$2,$5]=$4 next } { val=$1 SUBSEP $2 SUBSEP $9 } (val in a){ $2=b[val] $1=a[val] print $0,"R" next } { print $0,"O" }' Input_file1 Input_file2 我从Input_file1更改,那么就无法设置下一个元素,因为当前行的$ 1值是现已更改为Input_file1的$ 1。

答案 1 :(得分:0)

在gnu awk上尝试

 awk 'NR==FNR{r[NR]=$0;next} {x=split(r[FNR],a);if(a[1]==$1&&a[2]==$2&&a[5]==$9){$1=a[3];$2=a[4];print $0,"R",a[1],a[2]} else {print $0,"O",a[1],a[2]}}' file1 file2