首页 > 解决方案 > 如何从顶部文件或标准输出中删除 n 行(即撕掉它的标题)

问题描述

从一些不同长度的输出顶部删除 3 行(或其他)行的最简单的全局 shell 方法是什么?我意识到只有知道文档长度有多长,tail 才会起作用。

示例:假设我们要处理它但排除它的输出的前 2 行

$ curl -s http://google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

为了好玩,这里是 python 解决方案

$ curl -s http://google.com  | python -c "import sys; [sys.stdout.write(line) for line in list(sys.stdin)[2:]]" | sort
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
<H1>301 Moved</H1>
The document has moved

以这种方式扩展你的外壳

$ function from() {
> python -c "import sys; [sys.stdout.write(line) for line in list(sys.stdin)[${1}:]]"
> }

用任意数量的行来做到这一点

$ curl -s http://google.com  | from 3 | sort
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

标签: pythonhtmlshell

解决方案


我认为最简单和最“标准”的方式是使用tail:

curl ... | tail -n +4

tail 命令意味着打印从第 4 行开始的所有行(即跳过第 1 到第 3 行)。

如果你想要一个纯 bash 单线,你可以这样做:

lineno=1 ; curl ... | while IFS= read -r line ; do [ $lineno -gt 3 ] && echo "$line" ; lineno=$((lineno+1)); done

可能有一种比笨拙的 lineno 计数器更巧妙的方法,但它可以完成这项工作。


推荐阅读