shell - 如果来自一个文件的字符串并在另一个文件中搜索,如何读取列表?
问题描述
我正在尝试从一个文件中读取字符串列表并将其与第二个文件的第一列进行比较并打印整行。
我试过grep -f file1.txt file2.txt
但它比较整行中的字符串并打印它,我只想与第一列进行比较并打印该行
例如。
file1.txt
34534
67823
41400
file2.txt
41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 41400 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
78314 22540 60000 10250 20247 40083 82432
67823 41440 70000 10246 20231 39646 40092 71052 83531
输出是:
41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 <b>41400</b> 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
以下是预期输出:
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
41400 41440 52705 10254 20239 39975 40075 71022 82531
解决方案
我会使用awk:
$ awk 'NR==FNR{a[$0];next}($1 in a)' file1 file2
输出:
41400 41440 52705 10254 20239 39975 40075 71022 82531
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
解释:
$ awk ' # using awk
NR==FNR { # process the first file
a[$0] # hash words to a array
next # move to proces next word if any left
}
($1 in a) # if the first word of the second file record was hashed, output
' file1 file2
更新:
按file1.txt
使用顺序打印:
$ awk '
NR==FNR {
a[$1]=a[$1] (a[$1]==""?"":RS) $0 # catenate records based on $1
next
}
{
print a[$0]
}' file2.txt <(tac file1.txt)
上面的记录更改顺序演示了 bu 颠倒file1.txt
使用rev
. 以其他顺序输出:
67823 41440 70000 10246 20231 39646 40092 71052 83531
34534 41440 83203 10266 20255 40086 70262 84476
41400 41440 52705 10254 20239 39975 40075 71022 82531
推荐阅读
- azure - 以非 root 身份运行自定义脚本扩展
- sql-server - 需要更快的方法将大型 CSV 文件导入 Azure SQL Server DB
- bash - 搜索字符串模式并将其放在双引号中
- java - FusedLocationProvideClient 位置始终为空
- reactjs - 无法在我的组件中使用 useState 挂钩,我收到以下错误,
- python - 在数据集上应用内置和自定义创建的函数
- angular - 如何让 nav relativeTo 生效的激活路由?
- c++ - 如何让价格在 C++ 中一遍又一遍地增加?
- networking - Nmap关于更改端口后错误的服务名称
- bots - 我可以将机器人集成到 Zapier 中的 zap 中吗?