且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除使用bash / sed脚本的文本文件的第一行?

更新时间:2023-12-05 19:16:52

尝试的 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的或 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"

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

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.