从 grep 输出中获取关键字

Get key word from grep coutput

我有一个现有的基本脚本,无论我是 grep cat 还是 dog,我都需要从中获取 SERIAL 的值。像这样:

# grep dog | <additional commands>
123456789

剧本=animals.sh

#!/bin/bash

ANIMAL=

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

到目前为止我已经尝试了这些但是我仍在尝试研究如何继续或trim其他输出

[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 ~]$ 

如果awk是您的选择,请您尝试:

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

输出:

123456789

如果您更喜欢 grep 解决方案,这里有一个替代方案:

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

解释:

  • -P 选项启用 PCRE 正则表达式。
  • -o 选项告诉 grep 只打印匹配的子字符串
  • -z选项设置记录分隔符为空字符,启用 模式跨行匹配。

关于正则表达式:

  • dog[\s\S]+?SERIAL= 匹配一个最短的字符串(包括换行符) 在 dogSERIAL= 之间(含)。
  • \K 告诉正则表达式引擎丢弃前面的匹配项 匹配的模式。它可以清除 \K.
  • 之前的匹配模式
  • \d+ 匹配将作为结果打印的数字序列。