Issue
I have the following text input.txt
file
abc xyz 123
this is text
i dont need
abc def 123
this is text
i want to keep
and this also
{
contains
}
these lines
xyz
xyz
abc def ppp
this is also text
i want to keep
abc fff
this is text
i dont need
I want to keep only the text where the section starts with abc def
like below
abc def 123
this is text
i want to keep
and this also
{
contains
}
these lines
xyz
xyz
abc def ppp
this is also text
i want to keep
I have the command sed -n "/^abc def/,/^abc fff/p" input.txt
and got this:
abc def 123
this is text
i want to keep
and this also
abc def ppp
this is also text
i want to keep
abc fff
But i got 2 problems:
- it grabs the line
abc fff
- the marker to stop is not necessary
abc fff
, it can beabc fgh
Edit: I would like to remove the files from the input file.
Solution
Though you tagged your question with sed
, following gnu-awk
should be a good tool to get the job done:
awk -v RS='abc ' '$1 == "def" {print RT $0}' input.txt
abc def 123
this is text
i want to keep
and this also
{
contains
}
these lines
xyz
xyz
abc def ppp
this is also text
i want to keep
To store output in another file, use:
awk -v RS='abc ' '$1 == "def" {print RT $0 > "output"}' input.txt
To remove all matched text use:
awk -v RS='abc ' '$1 != "def" {ORS=RT; print $0 > "removed"}' input.txt
Answered By - anubhava Answer Checked By - Pedro (WPSolving Volunteer)