zeldor.biz

Linux, programming and more

Copyright © 2023
Log in

Sed replace text

June 21, 2010 by Igor Drobot Leave a Comment

Sed is available on all GNU/Linux distributions there is also a versions for Mac OS X too.
Typical usage of Sed are simple text replacement, testing for substrings, complex text replacement with regular expressions.

1
2
cat example.conf 
foo+bar=foo

cat example.conf foo+bar=foo

1
sed -i 's/foo/foo_bar/g' example.conf

sed -i 's/foo/foo_bar/g' example.conf

foo in file example.conf will be replaced with foo_bar

After replacement:

1
foo_bar+bar=foo_bar

foo_bar+bar=foo_bar

Start a dry run without changes, you will get a output about the changes (your file will stay untouched):

1
sed 's/192.168.0.1/nameserver.local/g' example.conf

sed 's/192.168.0.1/nameserver.local/g' example.conf

Append after match:

1
sed '/PATTERN_TO_SEARCH/a APPEND_ME' my_file

sed '/PATTERN_TO_SEARCH/a APPEND_ME' my_file

Remove line number 134 from file:

1
sed -i 134d /root/.ssh/known_hosts

sed -i 134d /root/.ssh/known_hosts

MAC OS X Section!

Sed inplace editing (-i) is a kind different on Mac OS X: in the normal UNIX case you will get a error:

1
2
id$ sed -i '/anna/ d' testfile
sed: 1: "testfile": undefined label 'estfile'

id$ sed -i '/anna/ d' testfile sed: 1: "testfile": undefined label 'estfile'

Soo this is the right syntax:

1
sed -i '' '/anna/ d' testfile

sed -i '' '/anna/ d' testfile

By the way, this will delete all lines which contains “anna” ;)

From the manpage: you risk corruption or partial content in situ-ations where disk space is exhausted, etc.

Filed Under: Linux Tagged With: Linux, regex, replace, sed

Categories

Archives

Tags

apache2 Apple arduino ARM Automation backup bash Cisco Cluster Corosync Database Debian Debian squeeze DIY DNS Fedora FTP Fun Icinga Ipv6 KVM Linux LVM MAC OS X Monitoring MySQL Nagios Nginx openSUSE OpenVPN PHP Proxy Python python3 qemu RAID rsync Samba security ssh Ubuntu virtualization Windows Windows 7 Wordpress

Leave a Reply

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