[英]Extract substring from string with sed
I want to extract MIB-Objects from snmpwalk output. 我想从snmpwalk输出中提取MIB对象。 The output
FILE
looks like: 输出
FILE
如下所示:
RFC1213-MIB::sysDescr.0.0.0.0.192.168.1.2 = STRING: "Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u1 (2017-06-18) x86_64"
RFC1213-MIB::sysObjectID.0 = OID: RFC1155-SMI::enterprises.8072.3.2.10
..
First, I read the output file, split at character =
and remove everything between RFC1213-MIB::
and .0
till the end of the string. 首先,我读取输出文件,将其分割为character
=
并删除RFC1213-MIB::
和.0
之间的所有内容,直到字符串结尾。
while read -r; do echo "${REPLY%%=*}" | sed -e 's/RFC1213-MIB::\(.*\)\.0/\1/'; done <$FILE
My current output: 我当前的输出:
sysDescr.0.0.0.192.168.1.2
sysObjectID
How can I remove the other values? 如何删除其他值? Is there a better solution of extracting
sysDescr
, sysObjectID
? 有更好的解决方案,提取
sysDescr
, sysObjectID
吗?
With awk: 使用awk:
awk -F[:.] '{print $3}'
(define :
and .
as field delimiters and display the 3rd field) (将
:
和.
定义为字段分隔符,并显示第三个字段)
with sed (Gnu): 与sed(Gnu):
sed 's/^[^:]*::\|\.0.*//g'
(replace with the empty string all that isn't a :
followed by ::
at the start of the line or the first .0
and following characters until the end of the line) (用空字符串替换所有这不是一个
:
接着::
在该行或第一开始.0
和以下字符到行的结尾)
Maybe you can try with: 也许您可以尝试:
sed 's/RFC1213-MIB::\([^\.]*\).*/\1/' $FILE
This will get everything that is not a dot ( .
) following the RFC1213-MIB::
string. 这将得到
RFC1213-MIB::
字符串后不是点( .
)的所有内容。
If you don't want to use sed, you can just use parameter substitution. 如果您不想使用sed,则可以使用参数替换。 sed is an external process so it won't be as fast as parameter substitution since it's a bash built in.
sed是一个外部过程,因此它不像参数替换那样快,因为它是内置的bash。
while IFS= read -r line; do line=${line#*::}; line=${line%%.*}; echo $line; done < file
line=${line#*::}
assumes RFC1213-MIB
does not have two colons and will be split from sysDescr
with two colons. line=${line#*::}
假定RFC1213-MIB
没有两个冒号,并且将从sysDescr
拆分为两个冒号。
line=${line%%.*}
assumes sysDescr
will have a .
line=${line%%.*}
假设sysDescr
会有一个.
after it. 之后。
If you have more examples, that you think won't work, I can update my answer. 如果您有更多示例,认为您无法使用,我可以更新答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.