Editing the file

Using the w flag, we can write our edits to a file, but what if we want to edit the file itself? We can use the -i option. We will need permissions to work with the file but we can make a copy of the file to work with, so we don't harm any system file or require additional access.

We can copy the passwd file locally:

$ cp /etc/passwd "$HOME"
$ cd 

We finish with the cd command to ensure that we are working in the home directory and the local passwd file.

The -i option is used to run an in-place update. We will not need the -n option or the p command when editing the file. As such, the command is as simple as the following example:

$ sed -i ' /^pi/ s@/bin/bash@/bin/sh/ ' $HOME/passwd 

There will be no output to the command but the file will now reflect the change. The following screenshot shows the command usage:

We should make a backup before we make the change by appending a string directly after the -i option and without any spaces. This is shown in the following example:

$ sed -i.bak ' /^pi/ s@/bin/bash@/bin/sh/ ' $HOME/passwd  

If we want to see this, we can reverse the search and replace strings:

$ sed -i.bak ' /^pi/ s@/bin/sh@/bin/bash/ ' $HOME/passwd  

This will set the local passwd file to be the same as it was before and we will have a passwd.bak with the previous set of changes. This keeps us safe with a rollback option if we need it.