sed replace string in file

Previous
Next

In this post, we will see how to replace String in file using sed in linux.

Problem

How to find and replace “Text1” with “Text2” using sed command in linux.

Solution

Sed stands for stream editor.It reads the file and modifies the file as provided by list of sed command.By default, input is written on the screen but you can update the file as well using -i option.

Here is simple command to replace string in file.

sed -i -e ‘s/old-string/new-string/g’ sample.txt

t
Here is the command of sed to find and replace String. It tells sed to find “old-string” and replace it with “new-string”. g/ means global replace. If you remove g from above command, sed will replace only first occurrence of old-string.

-e command
Append the editing commands specified by the command argument to the list of commands.
-i extension
Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

Let’s understand this with the help of a simple example.

$ cat > sample.txt

This is sample file

Java is programming language.
This is Java tutorial
I know Java very well.

Now let’s run sed command to find and replace “Java” with “Python”

$ sed -i -e ‘s/Java/Python/g’ sample.txt
$ cat sample.txt

This is sample file

Python is programming language.
This is Python tutorial.
I know Python very well.

Match word and then find and replace

Let’s say you want to find tutorial first and if line contains tutorial then only replace Python with Java.

$ sed -i -e ‘/tutorial/s/Python/java/g’ sample.txt
$ cat sample.txt

This is sample file

Python is programming language.
This is java tutorial.
I know Python very well.

Some problems with Sed

$ cat > site.txt

https://www.google.com is awesome search engine

You want to replace “https://www.google.com” with “https://www.bing.com”

$ sed -i -e ‘/s/https://www.google.com/https://www.bing.com/g’ site.txt

sed: 1: “/s/https://www.google.c …”: extra characters at the end of h command

You can // in your text which you want to replace, that’s why we are getting above error.
In this scenrio, you can use + instead of / for sed commands.

$ sed -i -e ‘s+https://www.google.com+https://www.bing.com+g’ site.txt
$ cat site.txt

https://www.bing.com is awesome search engine

That’s all about sed replace string in file.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog