Home > Net >  Get key word from grep coutput
Get key word from grep coutput

Time:03-20

I have an existing basic script that I need to get the value of SERIAL only from it whether I grep cat or dog. Like this:

# grep dog | <additional commands>
123456789

The script = animals.sh

#!/bin/bash

ANIMAL=$1

case "${ANIMAL}" in
        dog)
                echo ""
                echo "${ANIMAL} animal is chosen"
                SERIAL=123456789
                ;;
        cat)
                echo ""
                echo "${ANIMAL} animal is chosen"
                SERIAL=987654321
                ;;
        *)
                echo ""
                echo "wrong parameter applied"
                exit 1
                ;;
esac

So far I have tried these however I'm still trying to research on how to continue or trim the other outputs

[ec2-user@ip-192-168-100-101 ~]$ grep dog -A 3 animals.sh 
        dog)
                echo ""
                echo "${ENV} animal is chosen"
                SERIAL=123456789
[ec2-user@ip-192-168-100-101 ~]$ 

CodePudding user response:

If awk is your option, would you please try:

awk '
/dog/ {f = 1}                   # if the line matches "dog", set a flag
f && /SERIAL/ {                 # if the flag is set and the line matches "SERIAL"
    sub(".*SERIAL=", "")        # remove substring before the number
    print                       # print the result
    exit
}
' animals.sh

Output:

123456789

If you prefer grep solution, here is an alternative:

grep -Poz 'dog[\s\S] ?SERIAL=\K\d ' animals.sh

Explanation:

  • The -P option enables PCRE regex.
  • The -o option tells grep to print only the matched substring
  • The -z option sets the record separator to the null character, enabling the pattern match across lines.

About the regex:

  • dog[\s\S] ?SERIAL= matches a shortest string (including newline characters) between dog and SERIAL= inclusive.
  • \K tells the regex engine to discard preceding matches out of the matched pattern. It works to clear the matched pattern before \K.
  • \d matches a sequence of digits which will be printed as a result.
  • Related