Sed -i Command Examples in Unix and Linux

  • Updated
  • Posted in Programming
  • 2 mins read


Sed is useful gizmo for changing the textual content in a file. sed is a stream editor which suggests edit the file as a stream of characters. To substitute a textual content utilizing the unix sed command, you must cross the search string and substitute string. By default the sed command doesn’t edit the file and shows the output on the terminal.

We will see the utilization of -i command with an instance

Consider the under textual content file with knowledge

> cat file.txt
linux sed command tutorial

We will substitute the phrase “tutorial” with “instance” in the file utilizing the sed command.

> sed 's/tutorial/instance/' file.txt
linux sed command instance

> cat file.txt
linux sed command tutorial

The sed command changed the textual content in the file and displayed the end result on the terminal. However it didn’t modified the contents of the file. You can redirect the output of sed command and reserve it in a file as

> sed 's/tutorial/instance/' file.txt > new_file.txt

The -i possibility comes in useful to edit the unique file itself. If you utilize the -i possibility the sed command replaces the textual content in the unique file itself fairly than displaying it on the terminal.

> sed -i 's/tutorial/instance/' file.txt
> cat file.txt
linux sed command instance

Be cautious in utilizing the -i possibility. Once you modified the contents of the file, you can not revert again to the unique file. It is sweet to take the backup of the unique file. You can present a suffix to the -i possibility for taking the backup of the file. Now we are going to substitute the “instance” with “tutorial” and on the similar time will take the backup of the file.

> sed -i_bkp 's/instance/tutorial/' file.txt

> ls file.txt*
file.txt file.txt_bkp

> cat file.txt_bkp
linux sed command instance

> cat file.txt
linux sed command tutorial

See the backup file created with the contents of the unique file.

Recommended studying for you

Sed command Tutorial

Leave a Reply