我有一个包含以下行的文件。
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”。 由于换行符,这不起作用。应该有一些方法来实现这一目标。
答案 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