3

My encoder is a program that encodes a piece of text and prints the encoded text to the standard output. But when I do:

cat file.txt | encoder > file.txt

what happens is that all the text in file.txt is completely erased and there remains nothing in it.

Why does this happen? Is there something wrong with the command?

Note: There is nothing wrong with encoder. It works perfectly. I can achieve what I want with

cat file.txt | encoder > file2.txt

2 Answers 2

3

You want sponge ; it's in the moreutils package.

cat file.txt | encoder | sponge file.txt
3
  • but what is the problem with my command?
    – MichaelB
    Jul 17, 2013 at 20:11
  • 1
    The problem is that opening that redirect creates the file just before you read it. i.e. > file.txt makes a new file which replaces the file.txt you had.
    – Adrian
    Jul 17, 2013 at 20:27
  • Okay! So when the command it executed, the >file.txt part of the command causes it be opened and erased instantly. And now, because , there is nothing in the file, nothing is encoded and nothing is written to it! Hence sponge.
    – MichaelB
    Jul 17, 2013 at 20:43
0

You can use Vim in Ex mode:

ex -sc '%!encoder' -cx file.txt
  1. % select all lines

  2. ! run command

  3. x save and close

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .