0

I try to learn Unix and how to use the terminal. I am in a Mac

I open the terminal, I go to a folder. Inside there is the file fruit.txt. In that file there are only the words pear, apple

I want to substitute the word pear and put mango in the file fruit.txt

sed 's/pear/mango/' fruit.txt

the terminal gives me:

mango, apple

But I open the file and nothing changed. What am I missing?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
segon
  • 273
  • 1
  • 4
  • 16

1 Answers1

0

sed is a stream editor. This means that it reads data, changes it, and sends the result to output. It doesn’t automatically replace the contents of a file.

sed -i or sed --in-place will replace the file as you want.

Alternatively, you can do something like this:

sed fruit.txt > newfruit.txt

and the output will go to a new file. This is safer; if you make a mistake, you still have your original file.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
  • sed -i 's/pear/mango/' fruit.txt that gives me sed:1:"fruit.txt":invalid comand code f – segon Jan 22 '17 at 10:19
  • I also tried sed -i 's/pear/mango/' fruit.txt > newfruit.txt with the same result – segon Jan 22 '17 at 10:22
  • What version of `sed` do you have? `sed --version`. – Tom Zych Jan 22 '17 at 15:10
  • OP said they're on a Mac, so presumably it's BSD sed requiring `-i.bak` or similar. – Benjamin W. Jan 22 '17 at 19:40
  • @Tom Zych how can I now the version of sed? (I wrote sed --version in the terminal and it does not give me that) I am in a Mac. It seems that It is not possible to know the version: http://stackoverflow.com/questions/37639496/how-can-i-check-the-version-of-sed-in-os-x – segon Jan 24 '17 at 11:44
  • This works well: sed 's/oldword/newword/' file1.txt > file2.txt. Explanation here: http://stackoverflow.com/questions/7573368/in-place-edits-with-sed-on-os-x – segon Jan 24 '17 at 12:09