2015-11-06 121 views
-1

我需要幫助理解下面的代碼。爲什麼在這裏使用N和D?他們在這裏意味着什麼?Unix命令理解sed腳本

這是一個sed命令來打印重複的輸入行。

sort file | sed '$!N; s/^\(.*\)\n\1$/\1/; t; D' 
+4

您是否試過閱讀'sed'手冊頁? 'sed'手冊?在線指南'sed'?其中任何一個人都可以向你解釋'N'和'D'命令的作用。如果你有*閱讀這些和*仍然*不明白,然後表明並說明你有*作出(或至少試圖製造)的'sed'腳本的任何意義。 –

+2

您可以查看POSIX ['sed'](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html) 規範,或者查看「sed'變種的手冊在你的系統上。這兩個不一定匹配,但它們會顯示代碼。在所示的腳本中,「N」和「D」操作是簡單的操作。這是///'和't',它們更難以理解。 –

回答

2

這裏是稿件的翻譯:

for each line of input:  # sed does this loop automatically 

    if it's not the last line:  # This is what $! means 

     append a \n (newline) to the current line   # N means this 
     append the next line of input to the current line # and this 

    # Note that the "current line" may now contain a \n in the middle! 

    if the current line matches some string, followed by a \n, 
      followed by that same string again:    # s command's pattern 
     delete the \n and the second copy of the string  # s command's action 

    if the s command matched:  # t means this 
     go to endOfScript   # and this 

    delete everything up to the first \n in the current line # D means this 
    go to endOfLoop           # and this 

    endOfScript: 
    print the current line, followed by \n, to stdout # sed does this automatically 

    endOfLoop: 
    # just return to the top of the loop for the next line of input 

的d命令實際上是更復雜一點:它抑制了在循環頂部的下一行的閱讀,如果當前行有任何留下的字符。但是這個sed腳本從來就不是這種情況。

1

根據man page

N被指定讀取輸入的下一行/附加到模式 空間。

D刪除模式空間中的第一個嵌入換行符。 開始下一個週期,但如果模式空間中仍存在 數據,則跳過輸入讀取。

$匹配最後一行。

!標誌着自去年 輸入線讀取如果s///做了成功的替換不匹配的N

t label實際的定義和自上次tT命令,然後 分支標記;如果標籤被省略,則分支到腳本的結尾。