Use sed to print first n lines and last n lines of an output.

Use sed to print first n lines and last n lines of an output.
For example: n=10
Can it be done?
Thanks.

Check "selective printing of certain lines" section on this page

http://www.catonmat.net/blog/wp-content/uploads/2008/09/sed1line.txt

1 Like

Hi rajamadhavan, thanks for the reply.
I had seen the page before posting,
but below did not work. :frowning:

$ cat a.txt
1
2
3
4
5
6
7
$ sed 3q -e :a -e '$q;N;4,$D;ba' a.txt
/tools/oss/packages/x86_64-rhel5/sed/default/bin/sed: can't read 3q: No such file or directory
5
6
7

Is your need to print them at one go using a single sed command ?

Can't you go with something like this ?

sed '3q' filename &&  sed -e :a -e '$q;N;4,$D;ba' filename
1 Like

I know that you asked for a sed solution, but ed is well suited to something like this and only needs to be invoked once to do it. This was tested using a Korn shell, but will work with any shell that recognizes basic Bourne shell syntax:

#!/bin/ksh
# Usage: tester file count
ed -s "$1" <<-EOF
        1,$2p
        \$-$2+,\$p
        q
EOF

If you save this in a file named tester, make it executable with:

chmod +x tester

and run it with:

./tester a.txt 1

where a.txt contains the text shown in the 3rd message in this thread, the output will be:

1
7

and the output from the command:

./tester a.txt 5

will be:

1
2
3
4
5
3
4
5
6
7
2 Likes

Hi rajamadhavan,
Actually it's a command output instead of a file,
so your above code seems not applicable.
Thanks.

---------- Post updated at 02:50 PM ---------- Previous update was at 02:45 PM ----------

I googled and got some alternative solutions.

(head -3; tail -3) < a.txt

but how to apply it to a command output?
I tried below but failed.

cat a.txt | (head -3; tail -3)

Thanks.

Just for the fun of it, using awk

awk '{a[NR]=$0} NR<=n {print} END{for (i=NR-n+1;i<=NR;i++) print a}' n=3 file

This prints the first 3 and last 3 records of file

Or if you like it to the output
cat file | awk '{a[NR]=$0} NR<=n {print} END{for (i=NR-n+1;i<=NR;i++) print a}' n=3

1 Like

carloszhang,

Check it out : First n line and last n lines :

n=3;f=file;(head -n $n $f;tail -n $n $f)

with Classic ed:

n=3;printf "1,${n}p\n\$-${n}+,\$p\nq\n"|ed -s file
1 Like