Reputation: 5
I have a text file and want to extract all interfaces matching "blue"
random text random text random text
random text random text
int 1
random text
blue
random text
random text
int 2
random text
random text
red
random text
int 3
random text
random text
random text
blue
random text
random text
int 4
blue
random text
int n
random text
value
random text
random text random text random text
random text random text
Wanted output:
int 1
blue
int 3
blue
int 4
blue
int n
blue
(notice int 2 is "red" and therefore not displayed)
I've tried: grep "int " -A n file.txt | grep "blue" but that only display lines matching "blue". I want to also show the lines matching "int ". Also the section length can vary so using -A n hasn't been useful.
Upvotes: 0
Views: 480
Reputation: 11246
Another sed solution
Will work for multiple blues
sed -n '/^int/{x;/blue/{p;d}};/blue/H' file
random text random text random text
random text random text
int 1
random text
blue
blue
random text
random text
int 2
random text
random text
red
random text
int 3
random text
random text
random text
blue
random text
random text
int 4
blue
blue
blue
blue
blue
random text
int n
random text
value
random text
random text random text random text
random text random text
int 1
blue
blue
int 3
blue
int 4
blue
blue
blue
blue
blue
Upvotes: 2
Reputation: 10039
sed '/^int/ h
/^[[:space:]]*blue/ {x;G;p;}
d
' YourFile
added (post) constraint
Explication:
{x;G;p;}
(other action give the same depending of any other interest like H;x;p
or H;g;p
, in this case this is header destructive but it could be conservative using a s///
)Upvotes: 1
Reputation: 1034
An awk solution could be the following:
awk '/^int/{interface = $0} /blue/{print interface; print $0}' input.txt
It always saves the latest discovered interface. If blue
is found, it prints the stored interface and the line containing blue
.
Upvotes: 2
Reputation: 1726
one possible GNU sed solution
sed -n '/^int\|blue/p' file | sed -r ':a; N; $! ba; s/int \w*\n(int)/\1/g; s/int \w*$//'
output
int 1
blue
int 3
blue
int 4
blue
Upvotes: 1