Console logo</img>

Introduction to sed, “stream editor”, here you will see how to change words in text documents, using a console command line in Linux

Sed is a great tool to do a lot of things, the most known use of sed is to change words or strings in text documents, which is we are going to show here. Changing only the first occurrence in a sentence

In a given text document we are going to change only the first occurrence of the a given word in each sentence of the text, check this give text.

Hi,
This is a text document we are going to use to test sed, changing the word text into another word.

We are going to supply the other word to sed, and text should be changed to that word

In this line I am going to write twice text and text to show you how to change its first occurrence or globally.

This text file is saved as text.txt, so issue the command:

sed -i 's/text/human/' text.txt

The new file is:

Hi,
This is a human document we are going to use to test sed, changing the word text into another word.

We are going to supply the other word to sed, and human should be changed to that word

In this line I am going to write twice human and text to show you how to change its first occurrence or globlaly.

As you can see, only the first occurrence of the word text has been changed to human

Change the words globally

Well, now switch our file to its original point again.

sed -i 's/human/text/' text.txt

And now change it globally:

sed -i 's/text/human/g' text.txt

the new result is:

Hi,
This is a human document we are going to use to test sed, changing the word human into another word.

We are going to supply the other word to sed, and human should be changed to that word

In this line I am going to write twice human and human to show you how to change its first occurrence or globlaly.

Explaining a little how this works

We are using sed with the switch -s and this switch has this syntax.

From the man page:

s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

so s is the command / is the delimiter and the words inside delimiters are the strings to look for and change for, the g instructs sed to change the words or expressions globally.