我是bash脚本的初学者。我有一个包含内容的文件:
Section1 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = host1)(PORT = 1500)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
Section2 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = host1)(PORT = 1500)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
我想将Section1中的端口号更改为1600,并将“HOST = host1”替换为“Machine = machine2”。这是更改后的文件:
Section1 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = host1)(PORT = 1600)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
Section2 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(Machine = machine2)(PORT = 1500)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
由于
答案 0 :(得分:1)
将awk
与空记录分隔符一起使用:
awk -v RS= -v ORS='\n\n' '/^Section1/{sub(/PORT *= *[0-9]+/, "PORT = 1600")}
/^Section2/{sub(/HOST *= *host1/, "Machine = machine2")} 1' file
<强>输出:强>
Section1 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = host1)(PORT = 1600)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
Section2 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(Machine = machine2)(PORT = 1500)))
(CONNECT_DATA =
(SERVICE_NAME = service1)
)
)
答案 1 :(得分:1)
这是一个翻译要求的机械过程。
sed -e '/^Section1 =/,/^)/{ s/(PORT = [0-9]*)/(PORT = 1600)/; }' \
-e '/^Section2 =/,/^)/{ s/(HOST = host1)/(Machine = machine2)/; }'
在第1部分&#39;中,使用PORT = 1600
更改PORT值(无论原始值如何)。在第2部分&#39;中,将HOST = host1
部分更改为新值。如果你有GNU sed
,分号是可选的;如果您使用BSD(Mac OS X)sed
,则必须使用它们。因此,这应该适用于两者。