Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
1  
There is many useful sed scripts in one command line that you may need : sed one-line –  Slyx Jan 1 at 10:10

3 Answers 3

up vote 10 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 at 10:04
    
I have no idea how it works, but it works perfectly. Thanks a lot. –  Martin Vegter Jan 1 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
11
12
13
14
15
16
17
18
19
20

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

 
discard

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.