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.

while on bash, i tried to delete the 3 last columns of a file using:

head -n -3 file > file

but the file comes out empty. I can walkaround it but I would like to know what causes that.

Thanks a bunch!

share|improve this question
clarify: you want to remove columns as stated in the question or lines as used in head in your example? –  mnmnc Jan 7 '13 at 13:39

2 Answers 2

up vote 3 down vote accepted

Let's break down what that command does.

  1. > file

    This opens file for writing, and truncates it.

  2. head -n -3 file

    This reads all but the last 3 lines of file. Yes, the same file you truncated in step 1.

share|improve this answer

What you're trying to do is inline replacement, which isn't really possible without workarounds. In your command, the original file is overwritten because it's already opened and cleared when you send off the command.

Here are a couple of ideas:

  • Use a temporary file

    head -n -3 file > tmp
    mv tmp file
  • Use the sponge tool from moreutils, which soaks up all input and then writes to the file:

    head -n -3 file | sponge file
share|improve this answer
+1 for sponge, sounds great! –  terdon Jan 7 '13 at 13:50

Your Answer


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.