steve lin
steve lin

Reputation: 109

Suggestions to replace some text in the file

I am a beginner of bash script. I have a file with the content:

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

I want to change the port number in Section1 to 1600, and replace "HOST = host1" with "Machine = machine2". Here is the file after the change:

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

Thanks

Upvotes: 0

Views: 34

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

It's a mechanical process translating the requirements.

sed -e '/^Section1 =/,/^)/{ s/(PORT = [0-9]*)/(PORT = 1600)/; }' \
    -e '/^Section2 =/,/^)/{ s/(HOST = host1)/(Machine = machine2)/; }'

In 'Section1', change the PORT value (regardless of the original value) with PORT = 1600. In 'Section2', change the HOST = host1 section to the new value. The semicolons are optional if you have GNU sed; they're mandatory if you use BSD (Mac OS X) sed. This should work with both, therefore.

Upvotes: 1

anubhava
anubhava

Reputation: 784958

Using awk with empty record separator:

awk -v RS= -v ORS='\n\n' '/^Section1/{sub(/PORT *= *[0-9]+/, "PORT = 1600")} 
           /^Section2/{sub(/HOST *= *host1/, "Machine = machine2")} 1' file

Output:

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

Upvotes: 1

Related Questions