Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

You can use Vim in Ex mode:

ex -sc '-2,d|x' file
  1. -2, select last 3 lines

  2. d delete

  3. x save and close

share|improve this answer

You must log in to answer this question.

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