[英]Get the nth line from the bottom “safely”
给定一个文件:
dept4.abc.edu
dept3.abc.edu
dept2.abc.edu
dept1.abc.edu
我知道如何使用以下命令从底部获取第三行:
tail -3 file | head -1
只要文件长度大于或等于3行[ $(wc -l < file) -gt 3 ]
。 tail -4 file | head -1
tail -4 file | head -1
仍然可以,但tail -5 file | head -1
tail -5 file | head -1
不是我真正想要的。
我想知道是否有更好的方法和更干净的方法来安全地获取第n行,安全地说,我的意思是如果它不存在,请给我一个空字符串或错误。 有任何想法吗?
有很多方法可以从文件中获取第n行 ,请参见例如Bash工具,以从文件中获取第n行。
从文件底部获取第n行的最简单方法是使用tac ( cat
反函数)来反转文件。 像这样:
tac file | sed '3q;d'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.