To Overwrite a File Loaded on the Command Line

Asked 2 years ago, Updated 2 years ago, 93 views

$cathoge.txt>hoge.txt

I thought, "hoge.txt will be written to hoge.txt and eventually the contents will be the same," but when I try, the contents of the file will be empty and the capacity will be 0 bytes.

If you try to overwrite the read file with > in other commands, the contents disappear.

What should I do if I want to overwrite it?

linux unix

2022-09-30 19:49

4 Answers

After the shell interprets the command line, it opens hoge.txt to make it 0 bytes and then launches cat.You must copy hoge.txt to a temporary file before the command line you want to run, or overwrite the results after you print them to a temporary file.

In an environment where moreutils sponge(1) is available, you can run the following without the need for temporary files:

cat hoge.txt | sponge hoge.txt

Note that deleting the original file in the other answers may result in loss of file owner and access to the original file.


2022-09-30 19:49

Black magic, but only UNIX and shell features can be achieved without the need for intermediate files

(rm-f hoge.txt&cat>hoge.txt)<hoge.txt

Example using sort because cat is hard to understand:

%cathoge.txt
3
1
2
% (rm-f hoge.txt & sort > hoge.txt) <hoge.txt
% cathoge.txt
1
2
3

Even if you delete an open file, the file itself remains (readable and writable?) until it is closed.

Note: https://twitter.com/kuwashima/status/854716064109699072


2022-09-30 19:49

The redirect was handled by shell before the command was executed, so the file was already empty when the command was executed.

Don't you have no choice but to store the output in a separate file?

cathoge.txt>tmp
mvtmp hoge.txt


2022-09-30 19:49

GNU cat causes the syntax to fail.

$cathoge.txt>hoge.txt
cat:hoge.txt:input file is output file

How about doing the following?

$cathoge.txt | bash-c'cat->hoge.txt'


2022-09-30 19:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.