我正在用bash解析一个文件,我需要测试当前行是否像这样并提取“interface”之后的内容:
接口EthernetXXXX / YYY
或
interface port-channelZZZZZ
其中X,Y或Z是数字
文字示例:
channel-group 105 mode active
no shutdown
interface Ethernet4/20
description *** SW1-DT-A05-DC7 -> e1/37 ***
switchport
switchport mode trunk
switchport trunk native vlan 201
switchport trunk allowed vlan 1-394,396-1609
例如:
$REGEX = "^interface (REGEX)"
if [[ $line =~ $REGEX ]];
then
ifname = $XXX #the extracted part from the regex, i.e Ethernet4/20
fi
示例:
#!/bin/bash
filename = $1
vlan = $2
while read line; do
echo $line
$REGEX = "^interface (.*)"
$REGEX_VLAN = "switchport.*$vlan.*"
if [[ $line =~ $REGEX ]];
then
ifname = $XXX #the extraxted part from the regex
else
if [[ $line =~ $REGEX_VLAN ]];
then
echo "Interface $ifname contain the vlan $vlan"
fi
done <$filename
如果可能的话,你知道如何做到这一点吗?
答案 0 :(得分:2)
使用grep
和sed
怎么样?
grep interface test_sample | sed 's@interface\(.*\)@\1@'
grep
将使用界面搜索行,sed
将提取部分接口。您可以调整sed
正则表达式以完全符合您的需要
要使用提取部分,您可以使用for
循环:
for extract_part in $(grep interface test_sample | sed 's@interface\(.*\)@\1@')
do
# you can do what you want with extract part
echo $extract_part
done
另一种解决方案,无需调用外部流程:
while read -r line
do
if [[ $line =~ "interface "(.*) ]]
then
echo ${BASH_REMATCH[1]}
fi
done < "./test_sample"
答案 1 :(得分:0)
感谢你们两位。
这里是&#34; final&#34;关于我的问题的代码:
#!/bin/bash
filename=$1
vlan=$2
while read line; do
#echo $line
REGEX="^interface (.*)"
REGEX_VLAN="switchport.*$vlan.*"
if [[ $line =~ $REGEX ]];
then
ifname=${BASH_REMATCH[1]} #the extracted part from the regex
else
if [[ $line =~ $REGEX_VLAN ]];
then
echo "Interface $ifname contain the vlan $vlan"
fi
fi
done <$filename