尾部的对面:除最后n行之外的所有行

Han*_*örr 59 unix solaris tail unix-utils head

如何使用 unix 命令行过滤器丢弃文件的最后 n 行?

这将与以下情况相反tailtail丢弃前 n 行,但将其余行通过管道传输,但我希望该命令通过管道传输最后 n 行之外的所有内容。

不幸的是,我没有找到类似的东西 - 也head无济于事。编辑:至少在 Solaris 中它不接受否定论据。

更新:我最感兴趣的是适用于大文件的解决方案,即日志文件,您可能想要检查除了最后几分钟之外发生的情况。

小智 63

如果你有 GNU head,你可以使用

head -n -5 file.txt
Run Code Online (Sandbox Code Playgroud)

打印除最后 5 行之外的所有内容file.txt

如果head -n没有否定参数,请尝试

head -n $(( $(wc -l file.txt | awk '{print $1}') - 5 )) file.txt
Run Code Online (Sandbox Code Playgroud)

  • (并祈祷 `file.txt` 至少有六行长......) (17认同)
  • 遗憾的是,这个非 GNU 版本也不适用于流 (2认同)
  • 不适用于 Mac (2认同)

Kje*_* S. 23

head file.txt               # first 10 lines
tail file.txt               # last 10 lines
head -n 20 file.txt         # first 20 lines
tail -n 20 file.txt         # last 20 lines
head -20 file.txt           # first 20 lines
tail -20 file.txt           # last 20 lines
head -n -5 file.txt         # all lines except the 5 last
tail -n +5 file.txt         # all lines except the 4 first, starts at line 5
Run Code Online (Sandbox Code Playgroud)

  • 对无用信息的良好总结。已多次建议使用“负行号”(即前面带有 **```-```** 的行号),并且 OP 表示它在 Solaris 中不起作用。 (3认同)
  • 很好的总结 (2认同)

jwd*_*jwd 9

这是删除最后一行的简单方法,适用于 BSD 等。

sed '$d' input.txt
Run Code Online (Sandbox Code Playgroud)

该表达式为“在最后一行,将其删除”。将打印其他行,因为这是sed默认行为。

您可以将它们链接在一起以删除多行

sed '$d' input.txt | sed '$d' | sed '$d'
Run Code Online (Sandbox Code Playgroud)

诚然,这有点笨手笨脚,但只对文件进行一次扫描。

您也可以看看这个,以获得更多答案:https : //stackoverflow.com/questions/13380607/how-to-use-sed-to-remove-last-n-lines-of-a-file

这是改编自我最喜欢的一个的单线:

count=10
sed -n -e ':a' -e "1,$count"'!{P;N;D;};N;ba'
Run Code Online (Sandbox Code Playgroud)

我很高兴破译那个,我希望你也这样做(:它在N扫描时会缓冲行,但除此之外非常有效。

注意:!使用单引号引用以避免被 Bash 解释(如果那是你的 shell)。整个事情的简单双引号适用于sh,可能适用于其他人。


Mik*_*keL 6

MAC上获取除最后 N 行之外的所有行的解决方案:

head -n -5 file.txt
Run Code Online (Sandbox Code Playgroud)

将不起作用,因为您将收到以下错误:

head: illegal line count -- -5
Run Code Online (Sandbox Code Playgroud)

解决方案之一是安装 coreutils 并运行ghead

brew install coreutils
ghead -n -5 file.txt
Run Code Online (Sandbox Code Playgroud)

GNU Core Utilities 或 coreutils 是一个 GNU 软件包,其中包含许多基本工具的重新实现,例如 cat、ls 和 rm,这些工具在类 Unix 操作系统上使用。