Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Today I'm learning sort command.

I find that, I can use

sort file1 > file2

To inject the sorted file into file2

But when I use

sort file1 > file1

file1 become empty!

Why?!

I know I can use -o flag to get the sort file1 into file1.

But why the second command produce an empty file?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

Output redirection by the shell clears the file's contents before the sort command is run.

From man bash:

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. [...]

Redirection of output causes the file whose name results from the expansion of word to be opened for writing [...]. If the file does not exist it is created; if it does exist it is truncated to zero size.

share|improve this answer
    
So sorted writes an empty file into an empty file. –  Zen Jun 16 '14 at 9:27
1  
@Zen At least it'll be fast. :-) –  Daniel Beck Jun 16 '14 at 11:17
    
It's really a easy way to empty a file which its shell you want to keep. Just '> file' it –  Zen Jun 16 '14 at 11:24
    
I met a trouble now, as this method produce an empty file. How do I edit this file through command line? Like if I want to replace some words with sed. –  Zen Jun 20 '14 at 13:15
1  
@Zen If this is about sed, man sed will actually help you with this on the first page. –  Daniel Beck Jun 20 '14 at 15:12

As Daniel Beck has explained why that fails.

Here is a way to do that job the OP want.

sort file1 | tee file1

tee is a T-shape pipe which can write the buffer into the file and pass the buffer as output to the next pipe, here we just need to use its half power.

share|improve this answer
2  
Be careful, though. If the first command reads as a stream rather than buffer the whole file (sort does the latter, but others won't), then you'll have a similar problem. –  Bob Jun 24 '14 at 3:13
    
@Bob, I got you idea, like 'sed', so how can I modify a file safely in a command line? –  Zen Jun 24 '14 at 3:47
    
I suspect your only option for a generic method (i.e. where the command itself doesn't provide some way) is to manually create a temporary buffer, e.g. a temp file, and either write to this buffer + copy it back or copy the file and read from the copy. –  Bob Jun 24 '14 at 4:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.