Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

I have a mini-system with only limited number of binaries (bash,cp,cat,sed, ...). I don't have tail command, and I am wondering if I could emulate tail functionality with sed

cat foo.txt | tail -n 10

I know that I can print lines 1-10 with sed cat foo.txt | sed -n '1,10p', but how would I print the last 10 lines?

share|improve this question
There is many useful sed scripts in one command line that you may need : sed one-line – Slyx Jan 1 '14 at 10:10
up vote 11 down vote accepted

You could do something like this:

sed -e :a -e '$q;N;11,$D;ba'
share|improve this answer
sed -e :a -e '$q;N;11,$D;ba' foo to match the question. – Slyx Jan 1 '14 at 10:04
I have no idea how it works, but it works perfectly. Thanks a lot. – Martin Vegter Jan 1 '14 at 10:13
tac foo |  sed -n '1,10p' | tac

but if you don't have tac, you can use only sed this way :

sed -n '1!G;h;$p' foo | sed -n '1,10p' | sed -n '1!G;h;$p'
share|improve this answer

Is expr available with your system? Then you can try evaluating the desired line number after you have counted the total number of lines in the file.

I created a file named tmp containing the numbers from 1 to 20 in each line.

nlines=$(cat tmp | sed -n '$=')
cat tmp | sed -n $(expr $nlines - 9),"$nlines"p

Of course, you can use wc -l, if available.

The command to compute the total number of lines in the file is taken from sed one liners. However, I haven't checked if it works with empty files too.

P.S. If expr is not available, you can use subtract numbers in Bash as shown below:

cat tmp | sed -n $((nlines-9)),"$nlines"p
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.