Linux的头部/尾部有偏移量

有没有办法在Linux的要求头或尾,但有一个额外的logging偏移忽略。

例如,如果文件example.lst包含以下内容:

 row01 row02 row03 row04 row05 

我使用head -n3 example.lst我可以得到1 – 3行,但如果我想要它跳过第一行,并获得第2 – 4行呢?

我问,因为一些命令有一个头可能不是在search结果内。 例如du -h ~ --max-depth 1 | sort -rh du -h ~ --max-depth 1 | sort -rh将返回主目录中按降序排列的所有文件夹的目录大小,但会将当前目录附加到结果集的顶部(即~ )。

头部和尾部手册页似乎没有任何偏移参数,所以也许有某种range命令,可以指定所需的行:例如range 2-10或什么?

man tail

  -n, --lines=K output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth 

因此可以使用... | tail -n +2 | head -n 3 ... | tail -n +2 | head -n 3 ... | tail -n +2 | head -n 3从第2行开始获得3行。

非头部/尾部方法包括sed -n "2,4p"awk "NR >= 2 && NR <= 4"

要获取2到4之间的行(包括两者),可以使用:

 head -n4 example.lst | tail -n+2 

要么

 head -n4 example.lst | tail -n3 

这个解决方案花费了大量的时间,而这个解决方案似乎是唯一覆盖所有用例的解决方案(到目前为止):

 command | tee full.log | stdbuf -i0 -o0 -e0 awk -v offset=${MAX_LINES:-200} \ '{ if (NR <= offset) print; else { a[NR] = $0; delete a[NR-offset]; printf "." > "/dev/stderr" } } END { print "" > "/dev/stderr"; for(i=NR-offset+1 > offset ? NR-offset+1: offset+1 ;i<=NR;i++) { print a[i]} }' 

功能列表:

  • 活的输出为头(显然,对于尾巴是不可能的)
  • 不使用外部文件
  • stderr上的进度条,MAX_LINES之后的每行一个点,对于长时间运行的任务非常有用。
  • 避免由于缓冲而导致的错误日志顺序(stdbuf)