I want to use sed -n "/START PATTERN/,/END PATTERN/p" file.txt
pattern to search in a file.
file.txt
content is
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~3.~ ~output~.
~keyword blablabla~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~keyword blablabla2~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~3.~ ~not the output~.
~4.~ ~not the output~.
~blablabla~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~3.~ ~not the output~.
~4.~ ~not the output~.
What I expect as output is
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~3.~ ~output~.
So start pattern is keyword
in between ~
followed by any char .
so it is /~keyword~./
End pattern is ~
followed by any alphabetic characters and then any char .
.
When I run sed -n "/~keyword~./,/[~][[:alpha:]]./p" file.txt
the output is
~keyword~, ~output~.
~1.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.
2nd and 3rd lines is not printing in output so my question is what is wrong with my approach? I inspired this by using the solution provided here
I also tried sed "/~keyword~./,/[~][[:alpha:]]./!d;//d" file.txt
which results in empty output (inspired from this question)
This question is different with the question marked as duplicate because I asked specifily about use of sed for regular expression. Considering this, if you think it means it is duplicated, please mark it as duplicate.
Let's see if sed
is right tool for this job:
sed '/^~[[:alpha:]].*/!{ # if line doesn't match this pattern
H # append it to hold space
$!d # and delete it if it's not the last line
b end # else branch to label end
}
//b end # if line matches, branch to label end
: end # label end
x # exchange pattern space w. hold space
/^~keyword~.*/p # if pattern space matches, print it
d' infile # delete pattern space
With gnu sed
you could write it as a one-liner:
sed '/^~[[:alpha:]].*/!{H;$!d;b end};//b end;: end;x;/^~keyword~.*/p;d' infile
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments