Today this is another post on sed command in our blog. sed which is one of the famous and dynamic stream line editor use in Unix/Linux Operating System .

Along with sed command we can use many available option. One of the option is -i .

As per the manual page of sed command (Run `man sed` command in terminal) , the -i option is used for ‘edit files in place’ .

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

In common statement , insert the pattern/keyword Or edit into the file.s Without -i option the sed command shows the result output without editing or changing the original file content.

As a System Admin, it is common practice to take backup of file on which you are doing changes.
On fly we take backup commonly by using copy command (cp -p filename filename.date.bak)

We can do first backup of file and then use -i option with sed command to do changes in file.

Here is a time saving sed command for you. It will take backup automatically alongside you can do changes in file.

Syntax

sed "-i.bak" 's/Pattern-1/Pattern-2/g' /path/of/filename

NOTE: We are not limited with .bak suffix . We can use any suffix which is relevant to recognise file backup.

I mostly use date command.Which helps me to recognise on which date the file was taken backup.

EXAMPLE

Here I will use date command in suffix to print today’s date

sed "-i.`date +%F`" 's/Pattern-1/Pattern-2/g' /path/of/filename

Screenshot taken from my system.

sed

Read Some More Articles

2 Comments

  1. Don’t use “. That is deprecated as of a while ago, at least in Bash. POSIX standards say both can be used (which means if you have a machine that is not Bash but has a POSIX-standard shell, both should work). If you see “, please change it 😉 It gets to be very difficult to escape ` within “, unlike $() where you can keep on double quoting in the shell, and you do not need any quotes for assignment to a variable:

    local_var=$(my command “some string” $(another command))
    equivalent “: local_var=`my command “some string” `another command“ (hard to read and hard to remember such rules, much like trying to escape ‘ in ” (single quotes))

    http://wiki.bash-hackers.org/syntax/expansion/cmdsubst
    https://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution
    http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03

    1. Thankyou Tatsh,

      Very well said. You really made a good point.
      Thanks for highlighting

      Regards
      Sharad

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.