sed:删除文件的最后X行以外的所有行

Fel*_*rez 5 sed

可以使用其他工具完成,但我很想知道如何使用sed.

小智 9

基本上你是在模仿尾巴。在这个例子中 X = 20。以下示例将删除除最后 20 行之外的所有行:

sed -i -e :a -e '$q;N;21,$D;ba' filename
Run Code Online (Sandbox Code Playgroud)

解释:

  • -e :a 创建一个名为 a 的标签
  • 下一个 -e:
    • $q - 如果它是最后一行,则退出并打印模式空间
    • N - 下一行
    • 21,$D - 如果 line# >= 21(21,$ = 第 21 行到 $ 这是文件的结尾),则执行“D”命令
    • ba - 分支到标签“a”,这是脚本的开头。

  • +1...顺便说一句。如果将两个 `-e` 表达式压缩为一个,它可以与 `-i` 一起使用。您也可以通过将 bash 变量 `$1` 传递给它来使用它...... `sed -i ':a;$q;N;'$(($1+1))',$D;ba' filename` .. . 但要求`0` 行,将返回1 行。 (2认同)

Den*_*nis 6

sed当涉及到这样的任务时是相当复杂的。tailgrep或者awk会使这更容易,应该使用它。话虽如此,这可能的。

以下解决方案改编自sed 和 Multi-Line Search and Replace

sed -ni '
    # if the first line copy the pattern to the hold buffer
    1h
    # if not the first line then append the pattern to the hold buffer
    1!H
    # if the last line then ...
    ${
            # copy from the hold to the pattern buffer
            g
            # delete current line if it is followed by at least X more lines
            # replace X-1 with the proper value
            s/.*\n\(\(.*\n\)\{X-1\}\)/\1/
            # print
            p
    }
' filename
Run Code Online (Sandbox Code Playgroud)

没有评论,它是一个漂亮的单线。如果你想消除,例如,除最后十行之外的所有内容,请使用:

sed -ni '1h;1!H;${;g;s/.*\n\(\(.*\n\)\{9\}\)/\1/;p;}' filename
Run Code Online (Sandbox Code Playgroud)