-3

I am trying to modify a file using sed in a linux server (Ubuntu 16.04).

Here is an example of the code I am running:

sed 's/lineToChange/newString/' example.txt > example.txt

I feel like I should see newString in example.txt after executing this command since the result of the sed command (which prints newString when executed by itself without the redirect) is redirected to overwrite the example.txt content.

Unfortunately the file ends up empty when I do this...

My common sense is telling me that this should be right but clearly there is something I just don't understand here.

Thegree0ne
  • 175
  • 1
  • 2
  • 11
  • 2
    `>` have higher precedence. In other words `>` file redirection will happen at first. So, when `sed` try to process the file, it sees an empty file. Use `-i` (edit in-place) option in `sed`. Ex: `sed -i 's///' file` – sat Sep 02 '16 at 18:59
  • Thanks sat. That's a really good explanation. Karoly people like you makes other people uncomfortable of asking questions on stack overflow... thanks for the tip though because I never thought of googling it before asking it. – Thegree0ne Sep 02 '16 at 19:51

1 Answers1

2

If you want to edit a file inline, you should use the -i option:

sed -i 's/lineToChange/newString/' example.txt

This runs sed into a new file and moves that file to example.txt. Whenever you do ">", you essentially empty out example.txt which makes it empty for sed to work on.

archlyfe
  • 176
  • 10