2010-06-02 139 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