如何使用Sed在模式匹配之前删除5行之前和6行? [英] How to delete 5 lines before and 6 lines after pattern match using Sed?

查看:225
本文介绍了如何使用Sed在模式匹配之前删除5行之前和6行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文件中搜索模式xxxx,并在此模式之前删除5行,在此匹配之后删除6行。我如何使用Sed来做到这一点?

I want to search for a pattern "xxxx" in a file and delete 5 lines before this pattern and 6 lines after this match. How can i do this using Sed?

推荐答案

这可能适用于您(GNU sed):

This might work for you (GNU sed):

sed ':a;N;s/\n/&/5;Ta;/xxxx/!{P;D};:b;N;s/\n/&/11;Tb;d' file

5行窗口并遇到指定的字符串时,再添加6个(总共11个)并删除。

Keep a rolling window of 5 lines and on encountering the specified string add 6 more (11 in total) and delete.

注意这是一个准系统解决方案,很可能需要根据您的特定需求进行定制。问题如:如果整个文件中有多个字符串呢?如果字符串在前五行或者多个字符串在五行之内等等等等,那么该怎么办等等。

N.B. This is a barebones solution and will most probably need tailoring to your specific needs. Questions such as: what if there are multiple string throughout the file? What if the string is within the first five lines or multiple strings are within five lines of each other etc etc etc.

这篇关于如何使用Sed在模式匹配之前删除5行之前和6行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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