如何在Shell脚本中解析命令输出

16

请问有人能建议我如何解析下面的命令输出并将特定值存储在变量中吗?

sestatus

这是该命令的输出结果。

SELinux status:                 enabled  
SELinuxfs mount:                /selinux  
Current mode:                   enforcing  
Mode from config file:          enforcing  
Policy version:                 24  
Policy from config file:        targeted

我想把当前模式下的"强制执行"存储到一个变量中。

有人可以给我建议吗?

先行感谢。


谢谢大家...所有的回答都很有用。 - JSP
3个回答

13

你可以使用cut或sed工具,任何一种实现都足够使用。

[root@giam20 ~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 24
Policy from config file:        targeted
[root@giam20 ~]# variable=`sestatus | grep 'Current mode'|cut -f2 -d ":"`
[root@giam20 ~]# echo $variable
enforcing
[root@giam20 ~]#

这比上面的写法更简单。


8
您可以使用sed命令:
variable=$(the_command | sed -n 's/Current mode: \(.*\)/\1/p')
< p > $(cmd) 语法被称为命令替换,该语句将根据cmd的输出进行扩展。


6
你可以使用awk:
variable=`sestatus | awk '/Current mode:/ {print $3}'`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接