December 22, 2010

How to delete the last lines of a file

A friend of mine showed me a way to delete the last lines of a file after he read the article on how to delete the first lines of a file. The following is an example of how he did this with sed.

mike@shiner $ sed '$d' really_big_file.txt > new_file.txt

You'll need to use the single quotes to prevent the shell, such as bash, from interpreting $d as a variable. The '$' symbol matches the last line, similar to how it matches the end of the line in a regular expression. The 'd' tells sed that we want to delete the line.

Another way to do this, albeit not as elegant, is exemplified next.

mike@shiner $ tac really_big_file.txt | sed 1d | tac > new_file.txt

If you've never seen the tac command, it's similar to cat, but it's cat in reverse. I think it's kind of nifty that cat spelled backwards is tac. This helps with remembering the command.

Here's what I'm doing in each step:

1. cat the file in reverse.
2. Delete the first line.
3. cat the file in reverse again.
4. Save the output to 'new_file.txt'.

The end result is the same as before, but I can see someone arguing against it because of readability.

No comments:

Post a Comment