Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

bash - removing lines between two patterns (not inclusive) with sed

Ok

I know that this is trivial question but: How can i remove lines from files that are between two known patterns/words:

pattern1
garbage
pattern2

to obtain:

pattern1
pattern2

And does anyone known good(simple written!) resources for studying sed?? With many clear examples?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*
//}; p' inputfile

Explanation:

/pattern1/{         # if pattern1 is found
    p               # print it
    :a              # loop
        N           # and accumulate lines
    /pattern2/!ba   # until pattern2 is found
    s/.*
//        # delete the part before pattern2
}
p                   # print the line (it's either pattern2 or it's outside the block)

Edit:

Some versions of sed have to be spoon-fed:

sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*
//' -e '}' -e 'p' inputfile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...