Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all occurrences in 1 file with sed?

Tags:

linux

shell

sed

I need to replace all occurrences and write back to the same file

I tried:

sed 's/one/two/g' file.txt

this print out but does not write to file

I also tried

sed 's/one/two/g' file.txt>file.txt

This results in empty file

sed -i 's/one/two/g' file.txt

gives error: sed: 1: "file.txt": invalid command code f

Any idea?

like image 345
yarek Avatar asked Dec 13 '25 21:12

yarek


1 Answers

For Mac: Use -i.bak to add a backup file

sed -i.bak 's/one/two/g' file.txt

Or

sed -i '' 's/one/two/g' file.txt

For Linux: Use sed -i on to do infile substitution

sed -i 's/one/two/g' file.txt

You can also do something like below using a tmp file:

sed 's/one/two/g' file.txt > tmp.txt && mv tmp.txt file.txt
like image 154
Amit Verma Avatar answered Dec 15 '25 10:12

Amit Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!