How to search and replace a word in a file on Linux

There are many situations where we need to replace a word inside a file. Whether it's a service configuration file, a text file, or a file containing databases, in this tutorial you'll learn how to search and replace a word in a file on Linux.

How to search and replace a word in a file on Linux

The simplest option if you are an operating system user Linux, is to use the command “sed". Order for stream editor.

Let's say as an example that we have in a text file (document.txt) the word "abc” which we want to replace with “xyz". The command line by which we can replace the word will be the following:

sed -ie 's/abc/xyz/g' document.txt

When we execute the command, the condition is that we are in the folder where the file is located document.txt.

If the command is executed from another location, the full path of the file will be written. E.g:

sed -ie 's/abc/xyz/g' /full/path/document.txt

Where “/full/path/” is the folder where the file is located document.txt.

After running the command line, the option "-i" will create a backup file identical to the original one, but to the extension of which he will add the letter "e". In our case, the backup document will be document.txte.

-i[SUFFIX], --in-place[=SUFFIX] : edit files in place (makes backup if extension supplied)

-e script, --expression=script : add the script to the commands to be executed.

This order of “find & replace” is not valid only for files .txt. You can replace words inside any file that contains text. Even in database files (.SQL)

How to search and replace a word in a file on Linux
"sed" command in Linux

Stealth Settings - Find & Replace Inside a Text File (Linux Bash Command Line).

Founder and editor Stealth Settings, from 2006 to the present. Experience on operating systems Linux (in particular CentOS), Mac OS X, Windows XP> Windows 10 si WordPress (CMS).

How to » Linux » How to search and replace a word in a file on Linux
Leave a Comment