找到上下文后,用多行替换多行

时间:2014-07-18 16:31:38

标签: search replace

我有一个包含以下行的文件。

xyz_write =
(DESCRIPTION =
  (ADDRESS = (PROTOCOL = TCP)(HOST = hostname.com)(PORT = 80))
  (CONNECT_DATA =
    (SERVER = DEDICATED)
    (SID = database)
  )
)

我想找到xyz_write并替换它下面的行,直到找到下面的行为空行。

xyz_write =
(DESCRIPTION =
 (ADDRESS = (PROTOCOL = TCP)(HOST = hostname2.com)(PORT = 80))
 (CONNECT_DATA =
   (FAILOVER = TRUE)
   (SERVER = DEDICATED)
   (SID = database)
   (SERVICE = servicename)
  )
)

我尝试使用sed命令将第一组行存储在变量中,并将其替换为第二组行。但它没有帮助。我们怎样才能做到这一点?

我试过以下方法:

我将第一组行分配给变量,如下所示。

VARIABLE1="xyz_write =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname.com)(PORT = 80))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SID = database)
)
)" 

VARIABLE2="xyz_write =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname2.com)(PORT = 80))
(CONNECT_DATA =
(FAILOVER = TRUE)
(SERVER = DEDICATED)
(SID = database)
(SERVICE = servicename)
)
)". 

然后我尝试运行命令 “cat source_file.txt | sed”s / $ VARIABLE1 / $ VARIABLE2 / g“> destination_file.txt”。 由于换行符,这不起作用。应该有一些方法来实现这一目标。

1 个答案:

答案 0 :(得分:0)

文件filename.txt包含以下行

$ cat filename.txt

<blank line>
abc_write =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname2.com)(PORT = 80))
(CONNECT_DATA =
(FAILOVER = TRUE)
(SERVER = DEDICATED)
(SID = database)
(SERVICE = servicename)
)
)
<blank line>
xyz_write =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname2.com)(PORT = 80))
(CONNECT_DATA =
(FAILOVER = TRUE)
(SERVER = DEDICATED)
(SID = database)
(SERVICE = servicename)
)
)
<blank line>

我只想要一个上下文条目。对于“xyz_write”,我需要在文件中输入单个条目。在向文件添加新条目时,请检查它是否已存在。如果“xyz_write”已存在条目,则警告用户并使用新值更新条目。因此我想替换。不知何故,我通过删除现有条目并在文件末尾追加新条目来实现这一目标。

删除现有条目的命令。

\#This value is a command line input.
SERVICE_NAME="xyz_write" 

\#This will remove the existing entry. The command will delete the lines till empty line after the context. -i option will write to the same input file.

sed -i "/$SERVICE_NAME/,/^$/d" filename.txt

将新值附加到文件末尾。

NEW_VALUE="bcd_write
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname2.com)(PORT = 80))
(CONNECT_DATA =
(FAILOVER = TRUE)
(SERVER = DEDICATED)
(SID = database)
(SERVICE = servicename)
)
)"

echo $NEW_VALUE >>file_name.txt

因此我的目的就完成了。它实际上并没有取代多条线。它是通过删除现有线并附加新线来实现的。希望这有助于某人。

谢谢,
-Adithya