sed 或 perl + 在两行之间插入文本 [英] sed or perl + inserting text between two lines
问题描述
我有以下文件:(example.txt 显示)
I have the following file: (example.txt showing down)
我需要编辑文件,主要问题是在文件中的两个已知行之间附加文本
I need to edit the file , the main issue is to append text between two known lines in the file
first_line=")"
first_line=")"
second_line="NIC Hr_Nic ("
second_line="NIC Hr_Nic ("
例如
需要添加以下内容:
haattr -add RVG StorageRVG -string
haattr -add RVG StorageDG -string
haattr -add RVG StorageHostIds -string
haattr -delete RVG Primary
haattr -delete RVG SRL
haattr -delete RVG RLinks
之间
第一个匹配行)"
还有
第二个匹配行NIC Hr_Nic("
second match line "NIC Hr_Nic ("
如example.txt文件中所述
As described in example.txt file
如何通过 sed 做到这一点...(如果 sed 很难做到,那么使用 perl 也可以)
How to do this by sed ... (If its difficult by sed it can also possible with perl)
备注(sed需要获取两个参数第一个参数是第一个匹配行(first_line arg)第二个参数是第二个匹配行(second_line arg)
remark (sed need to get two arguments the first argument is the first match line (first_line arg) the second argument is the second match line (second_line arg)
example.txt 文件:
example.txt file:
group Hr_Grp (
SystemList = { london1 = 0, london2 = 1 }
AutoStartList = { london1, london2 }
)
NIC Hr_Nic (
Device = qfe0
)
IP Hr_Ip(
Device = qfe0
Address = "1.1.1.1" // Virtual IP
)
DiskGroup Hr_Dg(
DiskGroup = hrdg
)
RVG Hr_Rvg (
RVG = hr_rvg
DiskGroup = hrdg
)
Hr_Rvg requires Hr_Dg
Hr_Rvg requires Hr_Ip
Hr_Ip requires Hr_Nic
sed 编辑后的文件示例:
Example of the file after sed edit:
group Hr_Grp (
SystemList = { london1 = 0, london2 = 1 }
AutoStartList = { london1, london2 }
)
haattr -add RVG StorageRVG -string
haattr -add RVG StorageDG -string
haattr -add RVG StorageHostIds -string
haattr -delete RVG Primary
haattr -delete RVG SRL
haattr -delete RVG RLinks
NIC Hr_Nic (
Device = qfe0
)
IP Hr_Ip(
Device = qfe0
Address = "1.1.1.1" // Virtual IP
)
DiskGroup Hr_Dg(
DiskGroup = hrdg
)
RVG Hr_Rvg (
RVG = hr_rvg
DiskGroup = hrdg
)
Hr_Rvg requires Hr_Dg
Hr_Rvg requires Hr_Ip
Hr_Ip requires Hr_Nic
推荐答案
试试这个:
text=$(<file)
sed -e '/[[:blank:]]*)[[:blank:]]*/{:a;n;/NIC Hr_Nic (/i\' -e "$text" -e 'ba}'
我使用 i
进行插入和一个变量,因为 r
(读取文件)命令在当前行之后进行追加.您也可以像这样设置变量:
I'm using i
for insert and a variable since the r
(read file) command does an append after the current line. You can also set the variable like this:
read -d '' -r text<<EOF
haattr -add RVG StorageRVG -string
haattr -add RVG StorageDG -string
etc.
EOF
或
text="haattr -add RVG StorageRVG -string
haattr -add RVG StorageDG -string
etc."
这篇关于sed 或 perl + 在两行之间插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!