通过将字段与bash中的另一个csv文件进行匹配来在csv文件中添加列 [英] Append columns in csv file by matching the fields with another csv file in bash

查看:109
本文介绍了通过将字段与bash中的另一个csv文件进行匹配来在csv文件中添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个csv文件。 File1是现有的专用IP地址列表。它的主机名。 File2是每日报告,有8列,其中2列包含私有IP。
我想通过将文件2的字段4和7与文件1的字段2匹配来将文件2与文件1进行比较。然后,在匹配时,我想根据字段4和字段7与file1的字段2的匹配项来追加file2的字段3和字段6。

I have 2 csv files. File1 is an existing list of private IP address & its hostname. File2 is a daily report which has 8 columns in which 2 containing the private IP. I want to compare file2 with with file1 by matching field 4 and field 7 of file2 with field 2 of file1. Then, upon matching, I want to append field 3 and field 6 of file2 according to the matches of field 4 and field 7 with field 2 of file1.

File1.csv

File1.csv

PC1,192.168.3.1
PC2,192.168.3.2
PC3,192.168.3.3

File2.csv(大约50行)

File2.csv (Has about 50 lines)

Port,Type,S_Host,S_IP,Port,D_Host,D_IP,Port
2,tcp,N/A,192.168.3.1,2,N/A,192.168.3.2,8
3,tcp,N/A,192.168.3.2,2,N/A,192.168.3.3,3

我需要做一个bash脚本来使file2自动化。

I need to do a bash script to automate file2.

所需的输出:

Port,Type,S_Host,S_IP,Port,D_Host,D_IP,Port
2,tcp,PC1,192.168.3.1,2,PC2,192.168.3.2,8
3,tcp,PC2,192.168.3.2,2,PC3,192.168.3.3,3


推荐答案

如果您的输入文件是这样的,即第一个版本,逗号后面有空格:

If your input files look like this, i.e. the first version, with spaces after the comma:

File1.csv

File1.csv

Host, IP
PC1, 192.168.3.1
PC2, 192.168.3.2
PC3, 192.168.3.3

并且:

File2.csv

File2.csv

Port, Type, S_Host, S_IP, Port, D_Host, D_IP, Port
2, tcp, N/A, 192.168.3.1, 2, N/A, 192.168.3.2, 8
3, tcp, N/A, 192.168.3.2, 2, N/A, 192.168.3.3, 3

尝试:

#!/bin/bash
awk '
  BEGIN {FS = ", "; OFS = ", "}
  (FNR == NR) && (NR > 1) {hh[$2] = $1}
  NR > FNR {
    if (FNR == 1) 
      print; 
    else 
      print $1, $2, hh[$4], $4, $5, hh[$7], $7, $8;
  }
' File1.csv File2.csv

这是我的输出获取:

Port, Type, S_Host, S_IP, Port, D_Host, D_IP, Port
2, tcp, PC1, 192.168.3.1, 2, PC2, 192.168.3.2, 8
3, tcp, PC2, 192.168.3.2, 2, PC3, 192.168.3.3, 3




此外,如果IP是公共IP,则我需要进行Whois搜索以获取OrgName

Also, if the IP is a public IP, I need to do a whois search instead to get the OrgName

我建议您发布有关此第二个主题的另一个问题。就像在专业电子邮件中一样:一项等于一个问题。

I suggest you to post another question about this second topic. It is like in professional emails: one item = one question.

这篇关于通过将字段与bash中的另一个csv文件进行匹配来在csv文件中添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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