Sed to delete a range of lines from a specific mat

2019-02-08 16:37发布

I read through the forum for clues how to solve my problem, but none of the related threads are useable for me, with limited programming knowledge, to apply to my specific problem.

My problem is this: I need to get rid of garbage lines that are clustered throughout my file, but are in between clusters of useable lines. I searched the sed manual and other informative sources about deleting ranges that match patterns, but they only mention to delete UNTIL match pattern, not TILL.

Now I would like to specify a range for which sed deletes lines starting from the first line that matches the pattern line till the line that matches the other pattern. Furthermore, sed needs to recognize the patterns that exists at the end of the lines.

For example:

line 1
blah blah 1
blah blah 2
blah blah 3
blah blah 4
line 2
line 3

Result needs to be:

line 1
blah blah 1
line 2
line 3

Please note the multiple lines between line and and line 2. While blah blah 1 needs to stay, the other 3 need to be deleted.

Thanks!

标签: sed range
3条回答
闹够了就滚
2楼-- · 2019-02-08 17:19

Try this

sed -n '/line 1/{;p;n;p;};/line 2/,$p'  sedTest1.txt

#output
line 1
blah blah 1
line 2
line 3

Sed deconstructed :

 sed -n '/line 1/{;p;n;p;};/line 2/,$p'  sedTest1.txt
     |    |        |        |      |||-> print the range
     |    |        |        |      ||-> til end of file (the '$' char)
     |    |        |        |      |-> range operator (i.e. start,end)
     |    |        |        |-> beginning of range to watch for and print
     |    |        |-> now print line, get 'n'ext, print that line 
     |    |-> match the line with text 'line 1'
     |-> don't print every line, only ones flagged with 'p'

Read this from the bottom up.

Also, as your data is a sample, AND you refer to it as garbage lines, it may not be this simple. You'll need to look through sed tutorials to get up to speed.

I hope this helps.

查看更多
forever°为你锁心
3楼-- · 2019-02-08 17:22
$ sed -n '/line 1/{p;n;p;:a;n;/line 2/{:c;p;n;bc};ba};p' input.txt
line 1
blah blah 1
line 2
line 3
查看更多
淡お忘
4楼-- · 2019-02-08 17:27

This might work for you:

sed '/line 1/,/line 2/{//!d;/line 1/N}' file
line 1
blah blah 1
line 2
line 3

or this (if the ranges are not consecutive):

sed '/line 1/,/line 2/{//!d;$!N}' file
line 1
blah blah 1
line 2
line 3
查看更多
登录 后发表回答