9

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?

1
  • 2
    There is many useful sed scripts in one command line that you may need : sed one-line Commented Jan 1, 2014 at 10:10

3 Answers 3

18

You could do something like this:

sed -e :a -e '$q;N;11,$D;ba' 
5
  • sed -e :a -e '$q;N;11,$D;ba' foo to match the question. Commented Jan 1, 2014 at 10:04
  • I have no idea how it works, but it works perfectly. Thanks a lot. Commented Jan 1, 2014 at 10:13
  • 4
    Could someone explain this wonderful command ? I am looking to have one command that shows begginning and end of a document, and I think this command could help, but I need to add the head part. In fact, the command I was looking for is simply : sed -e '1,11p' -e :a -e '$q;N;11,$D;ba' But I'd still like to understand the tail part !!! Commented Jul 16, 2019 at 9:57
  • How might I alias sed -e :a -e '$q;N;11,$D;ba' in .bashrc? When I tried alias tsed="sed -e :a -e \'$q;N;4,$D;ba\'" it gives me: sed: -e expression #2, char 1: unknown command: `'' N: command not found 11,: command not found Commented Apr 19, 2021 at 7:32
  • 2
    Can you add bit explanation to options used? Thanks Commented Nov 11, 2021 at 18:45
0
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' 
-1

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 
1
  • 1
    1. Clearly misses the point of doing it in one pass; 2. UUoC; Commented Dec 9, 2021 at 13:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.