如何使用 Unix 从一行中删除第二次出现

How to delete second occurrence from a line using 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 

如何实现上面的预期输出?

我想这就是您要找的:

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

sed 可以使用 s/office//2 做到这一点。最重要的是,您可以将整个管道组合成一个命令。

sed -n '/Mandy/s/office//2p' file.txt

解释:

在上面的命令中有 2 个 sed 命令。

  1. /Mandy/ 仅在包含 Mandy.

    的行上运行下一个命令
  2. s/office//2p 删除(s用空字符串代替)2office 在这些行中,然后 p 打印它们。