linux - 从文件中读取模式,grep 仅第一次出现

标签 linux unix grep

<分区>

我正在从文件 appliances_list.txt 中读取一个字符串。

appliances_list.txt 包含

fridge
dryer
ironbox
microwave 

我正在阅读的文件是 myappliances.txt。内容是

I have a fridge
I have another fridge
I have a refridgerator
I have a microwave
I have ironbox at home
I have another microwave
I have a hairdryer

我在用

grep -o -m1 -f appliances_list.txt myappliances.txt

输出是

冰箱

我想要的输出是每个字符串的第一次出现(完全匹配)

fridge
microwave
ironbox

有人能指出我正确的方向吗?

最佳答案

一个使用 awk:

$ awk 'NR==FNR{a[$1]=1;next}a[$2]==1{print $2;a[$2]++}' pattern sample
Pattern1
Pattern2
Pattern3

解释:

$ awk '           # well, awk
NR==FNR {         # for the first file
    a[$1]=1       # hash each keyword and set it as 1
    next          # next record
}
a[$2]==1 {        # second file, if the word in 2nd column was hashed and 1
    print $2      # output it
    a[$2]++       # and increase its value above 1
}' pattern sample # mind the order

关于linux - 从文件中读取模式,grep 仅第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45970586/

相关文章:

php - 如何在 Windows 2003 上使用 PHP 将 ODBC 连接到 DB2?

c - 用于数据数组的 mmap 函数

python - Unix(Linux、FreeBSD)上如何获取系统库路径

python - Snakemake:从 DAG 可视化中隐藏某些规则

linux - 内置用于递归查找和替换的 unix/linux 命令?

python - 如何解决 Fenics 示例 ft06_elasticity.py 中名称 'nabla_div' 未定义错误?

Linux 启动时启用 USB 3G 调制解调器作为 ttyACM0 设备

c++ - 信号处理程序和本地状态

正则表达式:匹配以 4-9 开头的数字?

git - 在整个 git 存储库中搜索提交消息