I am writing a script that accepts as an argument a string. I want to run a particular command, check the output of that command for that input string, first returning lines that match on <input string>$
and only if that does not return any lines, then return all lines that contain <input string>
anywhere in the line. I am currently using grep -E
but am open to awk or sed
.
Consider this output written to file:
> cat command.out
A
A1
B
B1
B2
C1
C2
C3
XYZ
XYZ1
XYZ2
If my input string is 'B' then I want to return
B
not
B
B1
B2
If my input string is 'C' then I want to return
C1
C2
C3
If my input string is 'Z' then I want to return
XYZ
If my input string is 'Y' then I want to return
XYZ
XYZ1
XYZ2
Using a | (or) in the pattern doesn't do what I am after as it would return all lines with B.
What I have works but seems inefficient and I suspect there is a better way.
> command_output="$(cat command.out)"
> matches="$( (print "$command_output"|grep -E 'B$')||(print "$command_output"|grep -E 'B') )"
> print "$matches"
B
> matches="$( (print "$command_output"|grep -E 'C$')||(print "$command_output"|grep -E 'C') )"
> print "$matches"
C1
C2
C3
I have to persist the command output and fire off potentially two greps. I was hoping for a piped one-liner
matches="$(<run command>|grep <first pattern, if no match, second pattern>)"
but maybe that is not possible.