从 grep coutput 获取关键字
我有一个现有的基本脚本,无论我 grep cat 还是狗,我都需要从中获取 SERIAL 的值。像这样:
# grep dog | <additional commands>
123456789
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
到目前为止,我已经尝试过这些,但是我仍在尝试研究如何继续或修剪其他输出
[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 ~]$
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 ~]$
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
awk
是您的选择,请尝试:输出:
如果您更喜欢
grep
解决方案,这里有一个替代方案:说明:
-P
选项启用PCRE
正则表达式。-o
选项告诉 grep 仅打印匹配的子字符串-z
选项将记录分隔符设置为空字符,从而使跨行的模式匹配。
关于正则表达式:
dog[\s\S]+?SERIAL=
匹配最短的字符串(包括换行符)介于
dog
和SERIAL=
之间(含)。\K
告诉正则表达式引擎丢弃前面的匹配项匹配的模式。它的作用是清除
\K
之前的匹配模式。\d+
匹配将作为结果打印的数字序列。If
awk
is your option, would you please try:Output:
If you prefer
grep
solution, here is an alternative:Explanation:
-P
option enablesPCRE
regex.-o
option tells grep to print only the matched substring-z
option sets the record separator to the null character, enablingthe pattern match across lines.
About the regex:
dog[\s\S]+?SERIAL=
matches a shortest string (including newline characters)between
dog
andSERIAL=
inclusive.\K
tells the regex engine to discard preceding matches out of thematched pattern. It works to clear the matched pattern before
\K
.\d+
matches a sequence of digits which will be printed as a result.