bash – remove first line with tail and last line with head

This post is over 3 years old, so please keep in mind that some of its content might not be relevant anymore.

You can achieve the same result with other (more powerful) tools, but I like this approach because it’s the simplest I can think of.

Let’s say you have this text file called test.txt

line 1
line 2
line 3

Remove the first line

tail -n +2 test.txt
line 2
line 3

Remove the last line

head -n -1 test.txt
line 1
line 2

I used them directly on a file but keep in mind that they can always be used in one-liners like:

cat test.txt|tail -n +2|head -n -1
line 2

Hope it helps!
Andrea

Leave a Reply

Your email address will not be published. Required fields are marked *