【问题标题】:Get the nth line from the bottom "safely"从底部“安全地”获取第 n 行
【发布时间】:2014-06-17 15:00:30
【问题描述】:

给定一个文件:

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 -5 file | head -1 并不是我真正想要的。

我想知道是否有更好的方法和更清洁的方法来安全地获取第 n 行,安全地说我的意思是如果它不存在,只需返回一个空字符串或错误。有什么想法吗?

【问题讨论】:

  • 如果知道行号,可以使用sed 'NUMq;d' file
  • ...或者先用tac反转文件,再用sed '3q;d'
  • 谢谢,它有效! tac file | sed '5q;d'(假设文件末尾必须有一个空行)
  • @FredrikPihl 为什么不把它放在答案中:)
  • awk '{x[NR]=$0} END {print x[NR-2]}' file 也可以 :)

标签: bash shell head tail


【解决方案1】:

有很多方法可以从文件中获取第 n 行,参见例如Bash tool to get nth line from a file

从文件底部获取第n行的最简单方法是使用taccat的倒数)来反转文件。像这样的:

tac file | sed '3q;d'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多