0
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
Hassan Farid
  • 133
  • 2
  • 7

2 Answers2

2
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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
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.

Barmar
  • 741,623
  • 53
  • 500
  • 612