建议替换文件中的一些文本

时间:2016-02-16 15:12:33

标签: bash sed

我是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)
 )
)

由于

2 个答案:

答案 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,则必须使用它们。因此,这应该适用于两者。