简体   繁体   English

从 CLI 打印文件的最后一行

[英]Print the last line of a file, from the CLI

如何只打印文件的最后一行?

$ cat file | awk 'END{print}'

最初由Ventero回答

Use the right tool for the job.为工作使用正确的工具。 Since you want to get the last line of a file, tail is the appropriate tool for the job, especially if you have a large file.由于您想获取文件的最后一行,因此 tail 是适合该工作的工具,尤其是当您有一个大文件时。 Tail's file processing algorithm is more efficient in this case.在这种情况下,Tail 的文件处理算法效率更高。

tail -n 1 file

If you really want to use awk,如果你真的想使用awk,

awk 'END{print}' file

EDIT : tail -1 file deprecated编辑: tail -1 file已弃用

Is it a must to use awk for this?为此必须使用awk吗? Why not just use tail -n 1 myFile ?为什么不直接使用tail -n 1 myFile

Find out the last line of a file:找出文件的最后一行:

  1. Using sed (stream editor): sed -n '$p' fileName使用 sed(流编辑器): sed -n '$p' fileName

  2. Using tail: tail -1 fileName使用尾部: tail -1 fileName

  3. using awk: awk 'END { print }' fileName使用 awk: awk 'END { print }' fileName

You can achieve this using sed as well.您也可以使用sed来实现这一点。 However, I personally recommend using tail or awk .但是,我个人建议使用tailawk

Anyway, if you wish to do by sed , here are two ways:无论如何,如果你想通过sed来做,这里有两种方法:

Method 1:方法一:

sed '$!d' filename

Method2:方法二:

sed -n '$p' filename

Here, filename is the name of the file that has data to be analysed.这里,filename 是包含要分析的数据的文件的名称。

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

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