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 from A.txt.
问题:
回答1:
You don't. You use tail -n NUMLINES
for that.
tail -n 100 A.txt > B.txt
回答2:
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.
回答3:
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).