Linux头/尾有偏移

时间:2014-08-13 23:55:00

标签: linux bash shell command-line command

在Linux中是否有办法要求头部或尾部,但需要额外的记录偏移量来忽略。

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

row01
row02
row03
row04
row05

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

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

Head和Tail手册页似乎没有任何偏移参数,因此可能存在某种range命令,其中可以指定所需的行:例如range 2-10还是什么?

4 个答案:

答案 0 :(得分:38)

来自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从第2行开始获得3行。

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

答案 1 :(得分:4)

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

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

head -n4 example.lst | tail -n3

答案 2 :(得分:1)

sed -n 2,4p somefile.txt

#fill

答案 3 :(得分:0)

花了很多时间来结束这个解决方案,似乎是唯一覆盖所有用例的解决方案(到目前为止):

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)而导致错误的日志记录顺序