Categories: TutorialsUbuntu

Using sed to replace a string in a file

The ‘sed’ command can be used to easily replace all occurrences of one string in a text file, with another string.
For example:

sed -i "s/wordtofind/replacewithword/g" /path/to/file.txt

This command will find all occurrences of “wordtofind” and replace them on the fly with “replacewithword” in the file “/path/to/file.txt”.
The “-i” command switch specifies to edit the file in place, otherwise it will just display the output to the standard output. Run it without the “-i” switch to ensure it runs correctly, and makes the change you want, to prevent accidentally messing up your file.
You can also replace the whole line depending on your regular expression.
For

Sponsored
example:
sed -i "s/^myhostname.*/myhostname = your.hostname.here/g" /etc/postfix/main.cf

Assuming you have root permissions, this will replace the whole “myhostname” line from /etc/postfix/main.cf, and replace it with “myhostname = your.hostname.here”. You could have simply matched against the existing value, but if you wanted to script something to run on many machines, you are better off matching the beginning of the config line, as you wont always know the exact value you want to change.

Sponsored

The post Using sed to replace a string in a file appeared first on Networking HowTos.

Ubuntu Server Admin

Recent Posts

Kolla Ansible OpenStack Installation (Ubuntu 24.04)

Kolla Ansible provides production-ready containers (here, Docker) and deployment tools for operating OpenStack clouds. This…

13 hours ago

Canonical announces first Ubuntu Desktop image for Qualcomm Dragonwing™ Platform with Ubuntu 24.04

This public beta enables the full Ubuntu Desktop experience on the Qualcomm Dragonwing™ QCS6490 and…

2 days ago

The long march towards delivering CRA compliance

Time is running out to be in full compliance with the EU Cyber Resilience Act,…

2 days ago

Extra Factor Authentication: how to create zero trust IAM with third-party IdPs

Identity management is vitally important in cybersecurity. Every time someone tries to access your networks,…

3 days ago

Ubuntu Weekly Newsletter Issue 889

Welcome to the Ubuntu Weekly Newsletter, Issue 889 for the week of April 20 –…

4 days ago

From pidfd to Shimanami Kaido: My RubyKaigi 2025 Experience

Introduction I just returned from RubyKaigi 2025, which ran from April 16th to 18th at…

5 days ago