简体   繁体   English

bash脚本中的SED Escape

[英]SED Escape in bash script

My tempfile.txt has below contents [Typical Cisco Configuration File] 我的tempfile.txt具有以下内容[Typical Cisco Configuration File]

interface GigabitEthernet1/11
 no ip address
 shutdown
 rmon collection stats 6010 owner monitor
!
interface GigabitEthernet1/12
 no ip address
 shutdown
 rmon collection stats 6011 owner monitor
!
interface GigabitEthernet1/13
 no ip address
 shutdown
 rmon collection stats 6012 owner monitor
!
interface GigabitEthernet1/14
 no ip address
 shutdown
 rmon collection stats 6013 owner monitor
!

I am trying to loop through to do some operation on each block Example 我试图遍历每个块做一些操作

interface GigabitEthernet1/14 --> start of interface block
     no ip address
     shutdown
     rmon collection stats 6013 owner monitor
    ! --> end of interface block

I have another file which has below data intefaces.txt 我有另一个文件,其下面的数据为intefaces.txt

interface GigabitEthernet1/11
interface GigabitEthernet1/12
interface GigabitEthernet1/13
interface GigabitEthernet1/14

Now want to do some changes in each block thats why I am trying to access block in loop via 现在要在每个块中进行一些更改,这就是为什么我尝试通过以下方式循环访问块的原因

while read line
do
sed -n '/$line/,/!/p' tempfile.txt # this should get me block
#code for doing some changes in block
done < interfaces.txt 

Now since my $line will be one of line of interfaces.txt eg: interface GigabitEthernet1/11 现在,由于我的$ line将是interfaces.txt的行之一,例如: interface GigabitEthernet1/11

how can I escape / as I am doing in loop & my interfaces will always contain / character 我该如何逃避/正如我在循环中所做的那样-我的界面将始终包含/字符

通过在其前面加上反斜杠来告诉sed在搜索中代替/的字符:

sed -n "\@${line}@,/!/p" ...

To work with block of text, use gnu awk (due to multiple characters in RS) 要处理文本块,请使用gnu awk (由于RS中有多个字符)

awk -vRS="interface" '/1\/13/ {print RS $0}' file
interface GigabitEthernet1/13
 no ip address
 shutdown
 rmon collection stats 6012 owner monitor
!

Here you get all of info for interface 1/13 在这里您可以获得接口1/13所有信息


You can prevent the escaping of / by getting it in as a variable. 您可以通过将其作为变量输入来防止/的转义。

awk -vRS="interface" -vtest="1/13" '$0~test {print RS $0}'
interface GigabitEthernet1/13
 no ip address
 shutdown
 rmon collection stats 6012 owner monitor
!

In bash , you can use the parameter global replace operator, ${varname//old/new} , to replace the slashes with backslashed slashes, like this: bash ,可以使用参数全局替换运算符${varname//old/new} ,将斜杠替换为反斜杠,如下所示:

while read line; do
   sed -n "/${line//\//\/\/}/",'/!/p' tempfile.txt | # do stuff
done <interfaces.txt

... but Holy Leaning Toothpicks, Batman! ...但是圣洁的牙签,蝙蝠侠! I would go with @JonathanLeffler's solution of changing sed's search delimiter. 我会使用@JonathanLeffler的解决方案来更改sed的搜索分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM