bash - Unix: cat-ing a file out to itself - why does this blank the file? -


this question has answer here:

can please explain me why code works (i.e. file2.txt alphabetically sorted contents of file1.txt):

cat file1.txt | sort > file2.txt 

but when this, file1.txt blanks itself...?

cat file1.txt | sort > file1.txt 

as can guess, i'm trying sort file's contents alphabetically, write same file...

(i'm using mac 10.8.3's terminal. date of writing 19may2013)

the shell starts sort after opening file1.txt output (truncating it, ie discarding data). starts cat file1.txt open reading. semantics of shell such might feasible pipeline page or of input file.txt, in practice shells (which of them, perhaps there shells i've never used not behave way) truncate file before cat ever reads data.

to perform operation, must use temporary file. (well, it's not mandatory use temporary file. if file small enough, work cat file1.txt | ( sleep 2; sort > file1.txt ), not guaranteed.)


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -