如何删除使用bash / sed脚本的文本文件的第一行? [英] How can I remove the first line of a text file using bash/sed script?

查看:107
本文介绍了如何删除使用bash / sed脚本的文本文件的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要重复地从一个巨大的文本文件中使用bash脚本删除的第一行。

I need to repeatedly remove the first line from a huge text file using a bash script.

现在我使用 SED -i -e1D$文件 - 但它需要1分钟左右做删除

Right now I am using sed -i -e "1d" $FILE - but it takes around a minute to do the deletion.

有没有做到这一点更有效的方式?

Is there a more efficient way to accomplish this?

推荐答案

尝试的 GNU尾

tail -n +2 "$FILE"

-n X :只需打印最后 X 线。 尾-n 5 会给你最后的5号线的投入。在 + 签署样的反转参数,使打印任何东西,但第一个 X- 1 线。 尾-n +1 将打印整个文件,尾-n +2 的一切,但第一线,等等。

-n x: Just print the last x lines. tail -n 5 would give you the last 5 lines of the input. The + sign kind of inverts the argument and make tail print anything but the first x-1 lines. tail -n +1 would print the whole file, tail -n +2 everything but the first line, etc.

SED 快得多。 也可在BSD和 -n +2 标记是在这两个工具是一致的。检查 FreeBSD的或<一个href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html\"相对=nofollow> OS X 手册页以上。

tail is much faster than sed. tail is also available on BSD and the -n +2 flag is consistent across both tools. Check the FreeBSD or OS X man pages for more.

请注意:你可能会被使用。

Note: You may be tempted to use

# THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"

但是这会给你的空文件即可。其原因是重定向(&GT; )之前发生由外壳调用的:

but this will give you an empty file. The reason is that the redirection (>) happens before tail is invoked by the shell:


  1. 贝壳截断文件 $文件

  2. 壳牌创造了
  3. 一个新的进程
  4. 贝壳重定向工艺标准输出为 $文件

  5. 从现在空 $文件读取

  1. Shell truncates file $FILE
  2. Shell creates a new process for tail
  3. Shell redirects stdout of the tail process to $FILE
  4. tail reads from the now empty $FILE

如果您要删除该文件的第一行,你应该使用:

If you want to remove the first line inside the file, you should use:

tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"

&放大器;&安培; 将确保该文件不被覆盖时,有一个问题

The && will make sure that the file doesn't get overwritten when there is a problem.

这篇关于如何删除使用bash / sed脚本的文本文件的第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆