The code by Ghostdog doesn't work with me in bash. I admit, I don't understand the code either otherwise I would have tried to fix it.
In these cases, I think awk is your friend. I really pays off to grab the concept of awk. Once you do it only takes a few minutes to create a script for this kind of processing. Awk was written for this purpose.
Writing this post took me longer than writing the script.
This is the script:
Code:
BEGIN {
pflag=0
}
{
if ($0 ~ /YES_/){
pflag=0
}
if ($0 == flavour) {
pflag=1
}
if (pflag == 1 && $0 !~ flavour ){
print $0
}
}
With this input file
Code:
YES_CHICKEN
1. chicken chicken
2. chicken chicken
3. chicken chicken
4. chicken chicken
YES_HUMAN
1. human human
2. human human
3. human human
4. human human
YES_BIRD
1. bird bird
2. bird bird
3. bird bird
4. bird bird
yesfile is the input file containing your data strings. yes.awk is the awk script file.
it gives this output:
donald_pc:/tmp$ cat yesfile | awk -v flavour=YES_ -f yes.awk
donald_pc:/tmp$ cat yesfile | awk -v flavour=YES_m -f yes.awk
donald_pc:/tmp$ cat yesfile | awk -v flavour=YES_BIRD -f yes.awk
1. bird bird
2. bird bird
3. bird bird
4. bird bird
donald_pc:/tmp$ cat yesfile | awk -v flavour=YES_CHICKEN -f yes.awk
1. chicken chicken
2. chicken chicken
3. chicken chicken
4. chicken chicken
donald_pc:/tmp$
If you want the query string to show up before the data lines, change
if (pflag == 1 && $0 !~ flavour ){
in
if (pflag == 1){
On the command line, "-v flavour" passes a command line parameter to the awk script.
I know that there are awk gurus who can do this much more elegantly, and put it all on one line. This script is readable though
Let me know if this works for you
jlinkels