skip to Main Content
echo "hello" | tee test.txt
cat test.txt
sudo sed -e "s|abc|def|g" test.txt | tee test.txt
cat test.txt

Output:
The output of 2nd command and last command are different, where as the command is same.

Question:
The following line in above script gives an output, but why it is not redirected to output file?

sudo sed -e "s|abc|def|g" test.txt

2

Answers


  1. sudo sed -e "s|abc|def|g" test.txt | tee test.txt
    

    Reading from and writing to test.txt in the same command line is error-prone. sed is trying to read from the file at the same time that tee wants to truncate it and write to it.

    You can use sed -i to modify a file in place. There’s no need for tee. (There’s also no need for sudo. You made the file, no reason to ask for root access to read it.)

    sed -e "s|abc|def|g" -i test.txt
    
    Login or Signup to reply.
  2. You shouldn’t use the same file for both input and output.

    tee test.txt is emptying the output file when it starts up. If this happens before sed reads the file, sed will see an empty file. Since you’re running sed through sudo, it’s likely to take longer to start up, so this is very likely.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search