Removing lines between two patterns (not inclusive) with sed

OK

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

pattern1
garbage
pattern2

To obtain:

pattern1
pattern2

And does anyone know of good (simple written!) Resources for learning sed ?? With many clear examples?

+7
source share
6 answers
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile 

Explanation:

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

Edit:

Some versions of sed should be loaded with a spoon:

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

This might work for you:

 sed '/pattern1/,/pattern2/{//!d}' file 
+7
source

This is easy to do with awk:

 BEGIN { doPrint = 1; } /pattern1/ { doPrint = 0; print $0; } /pattern2/ { doPrint = 1; } { if (doPrint) print $0; } 

I found sed info a fairly simple read with many examples. The same goes for awk .

+4
source
 awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file 
+4
source

sed '/ PATTERN1 /, / PATTERN2 / d' FILE

+1
source

You can also use the Unix ed text editor:

 echo ' pattern1 garbage pattern2 ' > test.txt cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s test.txt &>/dev/null H /pattern1/+1,/pattern2/-1d wq EOF 

For more information, see Editing Files Using a Text Editor from Scripts

0
source

All Articles