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
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 thattee
wants to truncate it and write to it.You can use
sed -i
to modify a file in place. There’s no need fortee
. (There’s also no need forsudo
. You made the file, no reason to ask for root access to read it.)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 beforesed
reads the file,sed
will see an empty file. Since you’re runningsed
throughsudo
, it’s likely to take longer to start up, so this is very likely.