首页 > 解决方案 > 将 2 个文件内容与 shellScript 中的特定值进行比较

问题描述

我对 shell 脚本非常陌生,需要帮助我有 2 个文件,即

Student.txt
001、Peter、class3
002、Mohit、class4
等等……

Marks.txt
001, History, 45
001, Maths, 55
002, computer, 76
002, Maths, 96
等等
...例如,然后在另一个文件 Marks.txt 中搜索内容(卷号)第一个单词和第二个单词应该是“历史”,(条件:$1 == 卷号 && $2 == 历史)

我通过 awk cmd 并尝试但无法做出完整的解决方案

awk -F "," '{ print $1 }' student.txt awk -F "," '{ print $1, $2 }' 标记.txt

标签: shellawksed

解决方案


此命令首先从 Marks.txt 中收集第二列中具有历史记录的卷号,然后从 Student.txt 中打印具有此列表中卷号的行:

awk 'BEGIN {FS=", "} FNR==NR{ if ($2=="History"){a[$1];} next} $1 in a' Marks.txt Student.txt

输出:

001, Peter, class3

编辑:有关使用 awk 处理多个文件的更多信息,请参阅此内容:Using AWK to Process Input from Multiple Files


推荐阅读