[英]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.