Posts Use sed to find and replace
Post
Cancel

Use sed to find and replace

  • 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.