How To Use Sed To Replace a Specific String in a File

Ask , 0 Comments

Let’s take the linux shadow file as an example. Using sed you can replace the root user password with an empty character.

Suppose your /etc/shadow file look like this:

[root@localhost ~]# cat /etc/shadow
root:$6$GE3JYGgDvt5jloXN$l0cNhqsh8564GHsdSgUGz79Cqm2ml.Q0xmtgSDyUVdJRHrgFIWPd0QKB02RedspqunU4yYS0/xDI0fcZgEGt.::0:99999:7:::

You can use the following sed command to replace the root password string between the two semicolon with an empty string.

sed -e 's/root:[[:alnum:]]*[^:]*/root:/g' /etc/shadow

The string [[:alnum:]] in the sed command is a regex that mean : search for any alpha-numeric characters.

Use the -e to test the command before editing your file, to make change permanent use -i in you sed command.

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading...

Leave a Reply

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