Search Multiple patterns and display

Hi,

I have scenario like below and need to search for multiple patterns

Eg:

Test [Red]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc
Green test

Test[Yellow]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc
Green test

Output:

I need to display the text starting with Test and starting with Time in the sequence

Test [Red]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc

Test[Yellow]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc

Am trying with awk. But am able to search with only one pattern.

Thanks.

Three examples:

perl -ne '/^Test|^Time/ and print' weknowd.file
Test [Red]
Time Started= [2.3] secs
Time Ended = [4.5] secc
Test[Yellow]
Time Started= [2.3] secs
Time Ended = [4.5] secc
awk '$1 ~ /Test|Time/' weknowd.file
Test [Red]
Time Started= [2.3] secs
Time Ended = [4.5] secc
Test[Yellow]
Time Started= [2.3] secs
Time Ended = [4.5] secc
grep -E '^T(est|ime)' weknowd.file
Test [Red]
Time Started= [2.3] secs
Time Ended = [4.5] secc
Test[Yellow]
Time Started= [2.3] secs
Time Ended = [4.5] secc
1 Like

As long as empty lines between sets of data aren't important, you can also use:

sed -n '/^Test/,/Ended/p' file

and:

awk '/^Test/,/Ended/' file

both of which produce the output:

Test [Red]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc
Test[Yellow]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc

if file contains the data you showed us in post #1 in this thread.

If empty lines are critical between sets, you can try something a little more complex like:

awk '
/^Test/ {
	if(c++)	print ""
	p=1
}
p
/Ended/ {
	p = 0
}' file

which produces the output:

Test [Red]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc

Test[Yellow]
  Time Started= [2.3] secs
   Time Ended = [4.5] secc

The above script could be made slightly simpler if you want an empty line to be output after every set instead of just between sets in the output (i.e., add a trailing empty line to the output).
As always, if you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

1 Like