简体   繁体   English

如何在bash中打印文件末尾的第n行?

[英]how to print the nth line from the end of a file in bash?

Is there a way to print the nth line of a file, counting from the back of the file? 有没有办法打印文件的第n行,从文件的后面开始计算?

I know how to do it from the front of the file, but doing it from the back of the file seems to be more tricky. 我知道如何从文件的前面做到这一点,但从文件的后面做这件事似乎更棘手。

The quick and easy way is tail -n $n file | head -n 1 快捷方式是tail -n $n file | head -n 1 tail -n $n file | head -n 1 . tail -n $n file | head -n 1

A more fun way with awk is: 使用awk更有趣的方法是:

awk -v n=$n '{x[NR%n]=$0}END{print x[(NR+1)%n]}' file

If you have fewer than n lines, the tail | head 如果你的行数少于n行,则tail | head tail | head method will print the first line of the file, the awk way will print a blank line. tail | head方法会打印文件的第一行, awk方式会打印一个空行。

Quick and dirty, 100th line from the end: 快速而肮脏,从最后的第100行:

tail -n 100 yourfile | head -n 1

You'll get the first line of the file if it has less than 100 lines. 如果文件少于100行,您将获得该文件的第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM