简体   繁体   中英

How to replace all occurrences in 1 file with 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM