Post

Use sed to find and replace

Use sed to find and replace

sed in-place replacement is something I use in provisioning scripts where I need to modify config files programmatically. The g flag replaces all occurrences, not just the first. The -i.bck backup option is worth using — it saves you if the replacement pattern isn’t quite right and you need to revert.

  • Create a text file with some entries:
1
$ echo "Hello reader, how are you ?. Hope reader is doing well." > test.txt
  • View the contents of the file:
1
2
3
4
$ cat test.txt

Hello reader, how are you ?. Hope reader is doing well.

  • Test find and replace of only one occurance of word ‘reader’ with ‘rahul’
1
2
3
$ sed 's/reader/rahul/' test.txt

Hello rahul, how are you ?. Hope reader is doing well.
  • Test find and replace of all occurances of word ‘reader’ with ‘rahul’
1
2
3
$ sed 's/reader/rahul/g' test.txt

Hello rahul, how are you ?. Hope rahul is doing well.
  • Execute find and replace of all occurances of word ‘reader’ with ‘rahul’, with backup of original file
1
$ sed -i.bck 's/reader/rahul/g' test.txt
  • View the contents of the updated file:
1
2
3
$ cat test.txt

Hello rahul, how are you ?. Hope rahul is doing well.
  • View the contents of the backup file:
1
2
3
$ cat test.txt.bck

Hello reader, how are you ?. Hope reader is doing well.
This post is licensed under CC BY 4.0 by the author.