bash - 如何使用 AWK 或 GREP 比较两个文件
问题描述
所以我有两个问题,我有两个文件要排序和过滤。在这两个文件中,它们各有两列,其中 file1 有 IP 和端口,而 file2 有域和 IP。
file1:
Address,Port
1.2.3.4,8080
4.5.6.7,80
6.7.8.9,443
file2:
Domain,IP
google.com,1.2.3.4
google.fe,6.7.8.9
admin.ko,3.2.4.5
所以第一个问题:我想在 file1 中找到与 file2 中的任何 IP 都不匹配的 IP。
我尝试过使用 awk,这是我使用的:
awk -F',' FNR==NR{ a[$2]; next } !($1 in a)' file2 file1
所以我真的不太了解 awk,所以有人也可以帮助我理解您提供的 awk 命令的每个部分:)
Desired output:
Address,Port,Status
1.2.3.4,8080,Present
4.5.6.7,80,Not-Present
6.7.8.9,443,Present
下一个问题,我不知道怎么做,所以请帮忙。
第二个问题:所以我想列出与第一个相同的所需输出,但这次我想添加域列。
Desired output:
Address,Port,Domain,Status
1.2.3.4,8080,google.com,Present
4.5.6.7,80,NULL,Not-Present
6.7.8.9,443,google.fe,Present
先感谢您。
解决方案
以下是您提到的代码的完整说明,请仔细阅读。
awk -F',' ' ##Setting awk program here and setting comma as field separator for all lines here.
FNR==NR{ ##Checking condition if FNR==NR which will be TRUE when first Input_file named file2 is being read.
a[$2] ##Creating an array named a with index $2 of current line here.
next ##next will skip all further statements from here.
}
!($1 in a) ##Checking condition if $1 is NOT present from Input_file1 then print that line from Input_file1.
' file2 file1 ##Mentioning Input_file names here.
对于您的第二个问题,您可以尝试以下代码。
awk '
BEGIN{
FS=OFS=","
}
FNR==1{
if(++count==1){
val=$0
}
if(++count==2){
print val,$1,"Status"
}
next
}
FNR==NR{
a[$2]=$1
next
}
{
print $0,$1 in a?"Present":"Not-Present"
}
' file2 file1
推荐阅读
- javascript - Bootstrap 多选下拉菜单在 Apps 脚本中被部分 Html 视图隐藏
- java - 加载数据集后如何在 Apache spark java 中创建图形?
- linux - 每天记录(top、iotop、iostat)输出的实时数据的任何方式
- javascript - 发送签名消息
- reactjs - WebpackError:TypeError:在 Gatsby 构建期间无法读取未定义的属性“地图”
- swift - 如何在 Swift 5 中将“日期”转换为“数据”,反之亦然?
- mongodb - 在 Mongo Query 中更改字段的别名
- javascript - 从数据库中渲染数据
- nestjs - 如何在nest.js中的方法体上更改响应http状态码
- scala - 如何将简单的 scala 类序列化为 CSV 文件?