删除bash中的比赛之前和之后的行(使用sed或awk)? [英] Delete lines before and after a match in bash (with sed or awk)?

查看:87
本文介绍了删除bash中的比赛之前和之后的行(使用sed或awk)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从充满交易的文件中删除模式匹配两侧的两行. IE.找到匹配项,然后删除其前两行,然后删除其后两行,然后删除该匹配项.将此写回原始文件.

I'm trying to delete two lines either side of a pattern match from a file full of transactions. Ie. find the match then delete two lines before it, then delete two lines after it and then delete the match. The write this back to the original file.

所以输入数据是

D28/10/2011
T-3.48
PINITIAL BALANCE
M
^

我的模式是

sed -i '/PINITIAL BALANCE/,+2d' test.txt

但是,这仅是删除模式匹配后的两行,然后删除模式匹配.我无法找到任何合理的方法来使用sed从原始文件中删除所有5行数据.

However this is only deleting two lines after the pattern match and then deleting the pattern match. I can't work out any logical way to delete all 5 lines of data from the original file using sed.

推荐答案

sed会做到:

sed '/\n/!N;/\n.*\n/!N;/\n.*\n.*PINITIAL BALANCE/{$d;N;N;d};P;D'

它是这样工作的:

  • 如果sed在模式空间中只有一个字符串,则它会连接另一个字符串
  • 如果只有两个,它将加入第三个
  • 如果确实使用BALANCE补齐了LINE + LINE + LINE的模式,它将联接以下两个字符串,将其删除并从头开始
  • 如果不是,它将打印出模式中的第一个字符串并将其删除,并从头开始而不用滑动模式空间

为防止在第一个字符串上出现图案,应修改脚本:

To prevent the appearance of pattern on the first string you should modify the script:

sed '1{/PINITIAL BALANCE/{N;N;d}};/\n/!N;/\n.*\n/!N;/\n.*\n.*PINITIAL BALANCE/{$d;N;N;d};P;D'

但是,如果您要删除的另一个字符串PINITIAL BALANCE失败了.但是,其他解决方案也失败=)

However, it fails in case you have another PINITIAL BALANCE in string which are going to be deleted. However, other solutions fails too =)

这篇关于删除bash中的比赛之前和之后的行(使用sed或awk)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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