The -i flag in sed stands for in-place.
By default, sed is a "stream editor," meaning it transforms text and prints the result to your terminal (standard output) without changing the original file. When you add the -i flag, sed saves the changes directly to the file.
Comparison:
Without -i (Preview Only):
sed 's/Hi/Hello/' sed_test.txt
- The modified text is printed on your screen.
- If you run
cat sed_test.txtafterward, the file remains unchanged.
With -i (Save Changes):
sed -i 's/Hi/Hello/' sed_test.txt
- The terminal shows no output.
- The file
sed_test.txtis permanently updated with the new text.
Pro-Tip: Making Backups
Because -i overwrites your file immediately, it can be risky if your command isn't perfect. You can provide a suffix to the -i flag to create a backup original file:
sed -i.bak 's/Hi/Hello/' sed_test.txt
- This edits
sed_test.txtin-place. - It also creates a copy of the original file named
sed_test.txt.bakjust in case you made a mistake!
Caution: Always double-check your sed command without -i first to make sure it does exactly what you want before applying it to the file!