当前位置: 技术问答>linux和unix
大虾们救急!!关于shell字符串截取的问题
来源: 互联网 发布时间:2016-02-08
本文导语: 我自己得到了一个变量: UDP: = [127.0.0.2]:32774, SNMPv2-MIB::sysUpTime.0 = 137:13:37:06.22, SNMPv2-MIB::snmpTrapOID.0 = SNMP-MIB::Event.0.0, SNMP-MIB::componentName = "GUI", SNMP-MIB::eventCode = 3, SNMP-MIB::eventLevel = "Information", SNMP-MIB::eventArg...
我自己得到了一个变量:
UDP: = [127.0.0.2]:32774, SNMPv2-MIB::sysUpTime.0 = 137:13:37:06.22, SNMPv2-MIB::snmpTrapOID.0 = SNMP-MIB::Event.0.0, SNMP-MIB::componentName = "GUI", SNMP-MIB::eventCode = 3, SNMP-MIB::eventLevel = "Information", SNMP-MIB::eventArgs = "Web server start up on host: with port: in cluster ", SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = 10.60.56.114, SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = "public"
我想得到SNMP-MIB::eventCode后面的3和SNMP-MIB::eventArgs后面的字符串,请问我在bash里我应该怎么实现啊!!
这里先谢过各位了!
UDP: = [127.0.0.2]:32774, SNMPv2-MIB::sysUpTime.0 = 137:13:37:06.22, SNMPv2-MIB::snmpTrapOID.0 = SNMP-MIB::Event.0.0, SNMP-MIB::componentName = "GUI", SNMP-MIB::eventCode = 3, SNMP-MIB::eventLevel = "Information", SNMP-MIB::eventArgs = "Web server start up on host: with port: in cluster ", SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = 10.60.56.114, SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = "public"
我想得到SNMP-MIB::eventCode后面的3和SNMP-MIB::eventArgs后面的字符串,请问我在bash里我应该怎么实现啊!!
这里先谢过各位了!
|
awk -F ',' 'NR == 1{print $5 , $7}' test
SNMP-MIB::eventCode = 3 SNMP-MIB::eventArgs = "Web server start up on host: with port: in cluster "
可以打印出这两个字段,进一步的我也不会..
AWK 没有记忆功能,怕是不行.
sed 和 grep有的..
SNMP-MIB::eventCode = 3 SNMP-MIB::eventArgs = "Web server start up on host: with port: in cluster "
可以打印出这两个字段,进一步的我也不会..
AWK 没有记忆功能,怕是不行.
sed 和 grep有的..
|
#!/bin/bash
var='UDP: = [127.0.0.2]:32774, SNMPv2-MIB::sysUpTime.0 = 137:13:37:06.22, SNMPv2-MIB::snmpTrapOID.0 = SNMP-MIB::E
vent.0.0, SNMP-MIB::componentName = "GUI", SNMP-MIB::eventCode = 3, SNMP-MIB::eventLevel = "Information", SNMP-MI
B::eventArgs = "Web server start up on host: with port: in cluster ", SNMP-COMMUNITY-MIB::sn
mpTrapAddress.0 = 10.60.56.114, SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = "public"'
echo SNMP-MIB::eventCode:
echo $var | awk -F ', ' 'NR == 1{print $5 } ' | awk '{print $3}'
echo SNMP-MIB::eventArgs:
echo $var | awk -F ', ' 'NR == 1{print $7 } ' | sed 's/SNMP-MIB::eventArgs = //'
以上分别打印出eventCode和Args,前提是字符串中eventCode,Args在通过,分隔的位置不变。
var='UDP: = [127.0.0.2]:32774, SNMPv2-MIB::sysUpTime.0 = 137:13:37:06.22, SNMPv2-MIB::snmpTrapOID.0 = SNMP-MIB::E
vent.0.0, SNMP-MIB::componentName = "GUI", SNMP-MIB::eventCode = 3, SNMP-MIB::eventLevel = "Information", SNMP-MI
B::eventArgs = "Web server start up on host: with port: in cluster ", SNMP-COMMUNITY-MIB::sn
mpTrapAddress.0 = 10.60.56.114, SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = "public"'
echo SNMP-MIB::eventCode:
echo $var | awk -F ', ' 'NR == 1{print $5 } ' | awk '{print $3}'
echo SNMP-MIB::eventArgs:
echo $var | awk -F ', ' 'NR == 1{print $7 } ' | sed 's/SNMP-MIB::eventArgs = //'
以上分别打印出eventCode和Args,前提是字符串中eventCode,Args在通过,分隔的位置不变。