python - 如何从顶部文件或标准输出中删除 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>
解决方案
我认为最简单和最“标准”的方式是使用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 计数器更巧妙的方法,但它可以完成这项工作。
推荐阅读
- bash - 创建一个包含文件的目录 - bash 脚本
- django - 从一个应用程序获取字段名称到 django 中的另一个应用程序
- python - 随机森林提高准确性
- xml - 无法通过 XSLT 在属性值中插入换行符
- python - 熊猫,set_index + groupby 滚动
- r - Shiny - 如何判断图形何时以编程方式完成渲染?
- r - 基本 gganimate 导致“设备错误......未使用的参数(useS4 = FALSE)”
- javascript - Lightningchart JS 错误报告:仪表板交易示例,布林带的一部分消失了
- swift - Swift:后台应用程序刷新任务 - 如何查看任务是否成功运行
- r - 根据与另一列的部分匹配创建新列