首页 > 解决方案 > 如何使用 Unix 从一行中删除第二次出现

问题描述

我在文件中有以下数据

They used to carry lots of treats
but now they don’t have any sweets.
And so, if you’re in need of candy,
please don’t visit Mrs. Mandy. He is working in office.But will be late from office

例如 :

使用以下命令,我得到了作为同一行中的两个关键字的行

grep "Mandy" file.txt | grep "office"

上面的命令给了我下面的行作为输出

please don’t visit Mrs. Mandy. He is working in office.But will be late from office

现在从上面我得到的作为输出的行需要删除第二个出现的关键字:office并在输出下方打印

预期输出:

please don’t visit Mrs. Mandy. He is working in office.But will be late from 

如何实现上述预期输出?

标签: unixawksedgrepfind

解决方案


我认为这就是你要找的:

grep "Mandy" file.txt | grep "office" | grep -oP '.*(?=office)(?=office)'

这使用正则表达式和积极的前瞻。它产生您正在寻找的输出:

please don’t visit Mrs. Mandy. He is working in office.But will be late from

推荐阅读