Anyone here know AWK or SED?

I’m having a problem today at work remembering awk.

Say I’ve got a file with the lines:

This line doesn’t count;
The quick brown
fox jumped
over the lazy dog;
This line doesn’t count either;

how can I get the middle three lines from an awk script with just one command? I’ve done this before but I can’t remember the syntax and don’t have my awk book available.
Any help?

If I understand what you’re asking I would use sed instead of awk:

sed -e 1d -e 4q < file

You don’t need sed or awk. How about:


cat foo.txt | tail -4 | head -3

Or, what Perderabo said.

If you need to use sed or awk I can’t help you as I’ve forgotten both since I started using perl 4-5 years ago. One day I might get in trouble if I’m on a system without perl, but hopefully ‘man awk’ will be available and refresh my brain.

In perl, a generic program to print all but the first and last lines of a file of any size might look like


@a = <>;
shift @a;
pop @a;
print @a;

You could one-line this with


perl -e "@a=<>;shift @a;pop @a;print @a;" foo.txt

Of course, it’s perl, so there is more than one way to do it.

If you just want the middle 3 lines of 5 lines of text, this will do:


NR == 2 || NR == 3 || NR == 4 {print}