linux - 用于连接两列并在另一个文件中查找连接值的 awk 脚本

标签 linux bash awk scripting

需要你的帮助来解决这个难题。任何类型的帮助将不胜感激,并且任何文档的链接以供阅读和学习以及处理此类情况都会有所帮助

连接文件 1 的列 1 和列 2。然后检查文件 2 的列 1 中的连接值。如果找到提取File2的column2和column3的对应值,再次连接File2的column1和column2。现在在 File1 中查找这个串联值,如果找到的话

例如 - 连接 File1 的列 1(262881626) 和列 2(10)。然后在 File2 的第 1 列中查找这个串联的 (26288162610) 值,并提取 File2 的相应第 2 列和第 3 列值。 现在再次连接 File2 的第 1 列和第 2 列,并在 File1 中查找此连接值 (2628816261050),并将连接值 (26288162610) 获取的汇率 (2) 与对应于 File1 的 2628816261050 的应税值 (65) 相乘。仅将乘法值的结果存储在File1的第4列(AD)中

文件1

    Bill Doc     LineNo     Taxablevalue     AD
 262881626         10        245
 262881627         10        32
 262881628         20        456
 262881629         30         0
 262881630         40         45
2628816261050      11        65
2628816271060      12        34
2628816282070      13        45
2628816293080      14        0
2628816304090      15           

文件2

Bill.Doc     Item     Exch.Rate     
26288162610     50     2    
26288162710     60     1    
26288162820     70     45
26288162930     80     1    
26288163040     90     5

输出文件

 Bill Doc        LineNo  Taxablevalue   AD
262881626        10       245
262881627        10       32
262881628        20       456
262881629        30       0
262881630        40            
2628816261050     11      65            130
2628816271060     12      34            34
2628816282070     13      45            180
2628816293080     14      0              0
2628816304090     15

最佳答案

虽然您的输出不清楚,但请您尝试遵循并让我知道这对您有帮助。

awk -F"|" 'FNR==NR{a[$1$2]=$NF;next} {print $0,$1 in a?"|" a[$1]*$NF:""}' OFS=""   File2 File1

说明:

awk -F"|" '                         ##Setting field separator as |(pipe) here.
FNR==NR{                            ##Checking condition here FNR==NR which will be TRUE when first file named File2 is being read.
  a[$1$2]=$NF;                      ##Creating an array named a whose index is $1$2(first and second field of current line) and value if last field.
  next}                             ##next will skip all further statements from here.
{                                   ##Statements from here will be executed when only 2nd Input_file named File1 is being read.
  print $0,$1 in a?"|" a[$1]*$NF:"" ##Printing $0(current line) and then checking if $1 of current line is present in array a is yes then print a value * $NF else print NULL.
}
' OFS=""   File2 File1              ##Setting OFS to NULL here and mentioning both the Input_file(s) name here.

关于linux - 用于连接两列并在另一个文件中查找连接值的 awk 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616026/

相关文章:

linux - 如何在 ListView 中剪切 .txt 文件

c - forkpty - 套接字

git:一个快速命令去工作树的根

awk - 尝试 grep 字符串的输出行,然后返回 $3(第 3 列)+ 找到的字符串

bash - 在 awk 中使用记录分隔符

linux - 尝试运行服务时出现 systemctl Exec 格式错误

linux - 如何在 bash 脚本创建的文件中添加新行/回车符

bash - 我的 Bash 脚本有问题

java - 从java调用时bash脚本不等待命令完成

regex - Sed 动态反向引用替换