sed:刪除檔案中除最後 X 行之外的所有內容

sed:刪除檔案中除最後 X 行之外的所有內容

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

答案1

基本上你是在模仿尾巴。在此範例中 X = 20。以下範例將刪除除最後 20 行之外的所有行:

sed -i -e :a -e '$q;N;21,$D;ba' filename

解釋:

  • -e :a 建立一個名為 a 的標籤
  • 下一個-e:
    • $q - 如果是最後一行,則退出並列印模式空間
    • N - 下一行
    • 21,$D - 如果行號 >= 21,則執行「D」指令(21,$ = 第 21 行到 $,即檔案結尾)
    • ba - 分支到標籤“a”,這是腳本的開頭。

答案2

sed當涉及到這樣的任務時,是相當複雜的。tailgrep或者awk會使這變得更容易,應該改用。話雖如此,它可能的。

以下解決方案改編自sed 和多行搜尋和替換

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

沒有評論,它就成了一句漂亮的俏皮話。例如,如果您想要刪除除最後十行之外的所有內容,請使用以下命令:

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

答案3

基於中的腳本sed 手冊第 4.13 節你可以這樣做:

n=10

(( n > 1 )) && script='1h; 2,'$n'{H;g;}; $q; 1,'$((n-1))'d; N; D'
(( n > 1 )) || script='$!d'

sed -i "$script" infile

答案4

tac|sed|tac>&&(mv||cat>)

以下兩個命令片段將有效地刪除除最外的所有內容最後的5~/file1。如果您想保留最後的10,您可以替換:|sed '1,5!d;'|sed '1,10!d;',等等,如您認為合適。

  1. tac ~/"file1" |sed '1,5!d;' |tac >"/tmp/file2" &&mv  "/tmp/file2"  ~/"file1"
  2. tac ~/"file1" |sed '1,5!d;' |tac >"/tmp/file2" &&cat "/tmp/file2" >~/"file1"

相關內容