sed/awk删除字符串的第二次出现-与平台无关 [英] Sed/Awk to delete second occurence of string - platform independent

查看:331
本文介绍了sed/awk删除字符串的第二次出现-与平台无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找bash中可以在linux和OS X上都运行的行,以删除包含所需字符串的第二行:

I'm looking for a line in bash that would work on both linux as well as OS X to remove the second line containing the desired string:

Header
1
2
...
Header
10
11
...

应该成为

Header
1
2
...
10
11
...

我的第一次尝试是使用sed的删除选项:

My first attempt was using the deletion option of sed:

sed -i '/^Header.*/d' file.txt

但是,这也消除了第一次出现的情况.

But well, that removes the first occurence as well.

如何从给定的事件中删除匹配模式建议使用类似这样的内容:

How to delete the matching pattern from given occurrence suggests to use something like this:

sed -i '/^Header.*/{2,$d} file.txt

但是在出现错误的OS X上

But on OS X that gives the error

sed: 1: "/^Header.*/{2,$d}": extra characters at the end of d command

接下来,我尝试了替换,在该处我知道如何使用2,$,并且随后删除了空行:

Next, i tried substitution, where I know how to use 2,$, and subsequent empty line deletion:

sed -i '2,$s/^Header.*//' file.txt
sed -i '/^\s*$/d' file.txt

这在Linux上有效,但在OS X上有效,如此处所述

This works on Linux, but on OS X, as mentioned here sed command with -i option failing on Mac, but works on Linux , you'd have to use

sed -i '' '2,$s/^Header.*//' file.txt
sed -i '' '/^\s*$/d' file.txt

这反过来在Linux上不起作用.

And this one in return doesn't work on Linux.

那么我的问题是,没有一种简单的方法可以在任何Bash中使它起作用吗?不必sed,但应尽可能独立于外壳,并且我需要修改文件本身.

My question then, isn't there a simple way to make this work in any Bash? Doesn't have to be sed, but should be as shell independent as possible and i need to modify the file itself.

推荐答案

由于这是文件相关的,而不是行相关的,因此awk可能是更好的工具.

Since this is file-dependent and not line-dependent, awk can be a better tool.

只需对发生这种情况的次数进行计数:

Just keep a counter on how many times this happened:

awk -v patt="Header" '$0 == patt && ++f==2 {next} 1' file

这将跳过与给定模式完全匹配的行,并第二次执行该操作.在其余的行上,它可以正常打印.

This skips the line that matches exactly the given pattern and does it for the second time. On the rest of lines, it prints normally.

这篇关于sed/awk删除字符串的第二次出现-与平台无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆