Using SED to Get the Last n Lines of a Huge Text File

后端 未结 3 982
执念已碎
执念已碎 2021-01-04 18:38

How can I use \"sed\" command to get the last n lines of a huge text file (e.g. A.txt) and copy them into a new text file(e.g. B.txt)? I do not want to remove that lines fro

相关标签:
3条回答
  • 2021-01-04 18:54

    Here's how to use sed to print the last 10 lines of a file:

    sed -e :a -e '$q;N;11,$D;ba' 
    

    You should probably only use this if you're planning on executing more sed commands on these lines. Otherwise the tail command is designed for this job.

    0 讨论(0)
  • 2021-01-04 19:02

    Using GNU sed, here's how to get the last 10 lines:

    (For n lines, replace 11, with n+1)

    sed -ne':a;$p;N;11,$D;ba' A.txt > B.txt

    Note: On my Mac, with MacPorts, GNU sed is invoked as gsed. To use Apple's sed you would have to separate the label: sed -ne':a' -e'$p;N;11,$D;ba'*

    Explanation:

    sed -ne' invoke sed without automatic printing pattern space

    :a label for looping

    $p on last line, print pattern space, then quit

    N slurp the next line

    11,$D on line 11 through last line, remove the first line from pattern space (i.e. [^\n]*\n)

    ba' loop to :a

    Further

    Because of the loop, sed continuously appends the next line to pattern space. After line 11 and through the last line (11,$D) sed begins removing the first line from pattern space. At the last line the pattern space is printed (`$p'), which contains the last 10 most recently slurped lines (the last 10 lines of file A.txt).

    0 讨论(0)
  • 2021-01-04 19:15

    You don't. You use tail -n NUMLINES for that.

    tail -n 100 A.txt > B.txt
    
    0 讨论(0)
提交回复
热议问题