0

file1:

pattern1
a
b
c
end

cmd=>

cat file1 | sed -n '/pattern1/,/pattern2/p'

output=>

pattern1
a
b
c
end

How to not print the output if the second pattern does not match?

Desired output:

pattern1
3
  • Which second pattern?
    – pLumo
    Sep 30 '21 at 6:46
  • 2
    You don't need to pipe cat into sed. The latter can be used with the filename as an argument. As far as just print pattern1 from the file, that can be done with either the command that Kamil gave or with grep pattern1 filename.txt. As previously stated, the command that you have will give a syntax error. Sep 30 '21 at 7:24
  • It would be good if you could describe what the file can and cannot contain.  For example, can there be multiple pattern1-pattern2 pairs?  Can there be a pattern2 (or more than one) but no pattern1?  Can there be pattern1-pattern1-pattern2 or pattern1-pattern2-pattern2?  If you can rule out some combinations, more solutions might become possible. … … … … … … … … … … … … … … … … … … Please do not respond in comments; edit your question to make it clearer and more complete.
    – Scott
    Oct 7 '21 at 3:23
2

You need to buffer the text until you see the end "pattern" (horrible word btw - see how-do-i-find-the-text-that-matches-a-pattern), e.g. see the awk commands below:

$ cat file1
pattern1
a
b
c
end

$ sed -n '/pattern1/,/pattern2/p' file1
pattern1
a
b
c
end

$ awk '/pattern1/{f=1; print; buf=""; next} f{buf=buf $0 ORS; if (/pattern2/) {printf "%s", buf; f=0} }' file1
pattern1

$ awk '/pattern1/{f=1; print; buf=""; next} f{buf=buf $0 ORS; if (/end/) {printf "%s", buf; f=0} }' file1
pattern1
a
b
c
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.