2012-03-29 37 views
4

下一個班輪打印出來的文件反向你能解釋一下這個sed單線嗎?

$ sed -n '1!G;h;$p' test.txt 

內容時sed的逐行讀取文件中的行這怎麼可能?你能解釋的

  • n標誌
  • 1!
  • G
  • h
  • $p

在這個命令的含義?

+2

http://www.thegeekstuff.com/2009/12/unix-sed-tutorial-7-examples-for-sed-hold-and-pattern-buffer-operations/ – perreal 2012-03-29 21:34:34

+0

爲什麼要刪除http:// stackoverflow.com/questions/9936151/piping-bash-input-arguments-in-egreps-regular-expression?我認爲這是一個很好的問題,並得到了很好的答案。 – sarnold 2012-03-30 02:41:23

+1

N.B.另一種方式寫這個是'sed'1!G; h; $!d'' – potong 2012-03-30 07:11:53

回答

6

這將執行與tac相同的工作,即恢復行的順序。 重寫sed腳本僞代碼,這意味着:

$line_number = 1; 
foreach ($input in $input_lines) { 
    // current input line is in $input 
    if ($line_number != 1)    // 1! 
     $input = $input + '\n' + $hold; // G 

    $hold = $input; // h 

    $line_number++ 
} 

print $input; // $p 

正如你所看到的,SED語言:-)的1!$是所謂的地址,裏面放的條件非常傳神當命令應運行。 1!表示不在第一行,$表示最後。 Sed有一個輔助存儲器寄存器,稱爲hold space

欲瞭解更多信息在Linux控制檯鍵入info sed(這是最好的文檔)。

-n在循環中禁用默認的print $input命令。

術語pattern spacehold space分別是在本例中變量$input$hold(分別)的等同物。

+0

謝謝你的回答!驚人的解釋 – Alby 2012-03-29 22:32:32

+1

謝謝@Alby - 剛剛添加了關於'-n'命令選項的註釋,並在模式/保持空間中添加了一個註釋。 – TMS 2012-03-29 22:39:20

+0

你的僞代碼在變量上仍然有sygils?獲得專業幫助。 :) :) :) – Kaz 2012-03-29 23:12:46

5
n flag -> Disable auto-printing. 
1!  -> Any line except the first one. 
G  -> Append a newline and content of 'hold space' to 'pattern space' 
h  -> Replace content of 'hold space' with content of 'pattern space' 
$  -> Last line. 
p  -> print 

所以,這意味着:扭轉文件的內容,據我瞭解。


編輯添加一些說明(感謝波東,看到他對原來的註釋):

地址,像1$必然要下一個命令,利用分組{...}或單身沒有他們。所以在這種情況下,1!適用於G$p,而h未附加到地址並適用於所有地址。那是$!G$!{G}是一樣的。

+0

謝謝你的回答。我可以問一下「保持空間」和「圖案空間」是什麼? – Alby 2012-03-29 22:29:11

+2

@Alby:在'sed'中,你通常使用模式空間(例如:你對模式空間進行替換),它保存從輸入讀取的行。還有一個保留空間,您可以在其中明確地存儲(保存)和檢索事物,以允許更復雜的sed腳本。 – ninjalj 2012-03-30 00:33:32

+0

@ninjalj:謝謝你的解釋,+1 – Birei 2012-03-30 06:33:29

相關問題