2010-06-02 95 views
5

如標題所示,我試圖只改變第一次出現的單詞。通過使用 sed的/ this/that /'文件。 txtsed's/this/that /' - 忽略g但仍然替換整個文件

雖然我沒有使用g選項,它取代了整個文件。如何解決這個問題。?

UPDATE:

$ cat file.txt 
    first line 
    this 
    this 
    this 
    this 
$ sed -e '1s/this/that/;t' file.txt 
    first line 
    this // ------> I want to change only this "this" to "that" :) 
    this 
    this 
    this 
+0

你不能用我的回答給予了充分的SED的例子。我測試過它併爲我工作。 – zaf 2010-06-02 09:40:04

回答

6

http://www.faqs.org/faqs/editor-faq/sed/

4.3。如何更改模式的第一次出現?

sed -e '1s/LHS/RHS/;t' -e '1,/LHS/s//RHS/' 

這裏LHS = this和RHS =對於你的例子。

如果你知道不會第一行出現的模式,省略了第一-e和它後面的語句。

+0

請檢查我上面的示例。 – 2010-06-02 09:34:02

+0

你沒有使用我測試過的完整sed示例,併爲我工作。 – zaf 2010-06-02 09:37:30

+0

謝謝使用-e works-sed -e'1s/LHS/RHS /; t'-e'1,/ LHS/s // RHS /' – 2010-06-02 09:47:43

1

sed本身通過應用編輯通過文件並結合「g」標誌編輯應用於同一行上的所有出現。

例如

$ cat file.txt 

    first line 
    this this 
    this 
    this 
    this 

$ sed 's/this/that/' file.txt 
    first line 
    that this 
    that 
    that 
    that 

$ sed中的/這/那/ G'file.txt的

first line 
    that that <-- Both occurrences of "this" have changed 
    that 
    that 
    that