sed: Editing text files

Hi,

here some often requested basic examples on how to edit text files with sed.

An example file, here a NetworkManager interface config, filename config.net:
[connection]
id=int_with_static_routes
uuid=75241683-27b0-125e-666a-b58823c177d14d
type=ethernet
autoconnect-priority=-999
interface-name=eth0
permissions=
timestamp=1534541432

[ethernet]
mac-address-blacklist=

[ipv4]
dns-search=
method=auto
route1=192.168.192.234/32,10.10.254.10,1
route2=192.168.201.1/32,10.10.254.10,1

By default sed writes to stdout, to console. If you want to edit the file directly append –in-place=.bak. This also creates a backup file of the file before editing.

Replace the first match (first match means first match in line). sed proceeds line by line.

sed -e's/192/172/' config.txt


...
method=auto
route1=172.168.192.234/32,10.10.254.10,1
route2=172.168.201.1/32,10.10.254.10,1

Replace all matches in a line

sed -e's/192/172/g' config.txt


method=auto
route1=172.168.172.234/32,10.10.254.10,1
route2=172.168.201.1/32,10.10.254.10,1

Append a line after a match => a switch

sed -e'/route1=192.168.192.234\/32,10.10.254.10,1/a route2=192.168.230.34\/32,10.113.56.148,1' config.txt


...method=auto
route1=192.168.192.234/32,10.10.254.10,1
route2=192.168.230.34/32,10.113.56.148,1
route2=192.168.201.1/32,10.10.254.10,1

Add a line before a match => i switch

sed -e'/route1=192.168.192.234\/32,10.10.254.10,1/i route0=192.168.230.34\/32,10.113.56.148,1' config.txt


...
method=auto
route0=192.168.230.34/32,10.113.56.148,1
route1=192.168.192.234/32,10.10.254.10,1
route2=192.168.201.1/32,10.10.254.10,1

Michael

Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.