5

as title said, Im trying to change only the first occurrence of word.By using sed 's/this/that/' file.txt

though i'm not using g option it replace entire file. How to fix this.?

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
zaf
  • 22,776
  • 12
  • 65
  • 95
webminal.org
  • 44,948
  • 37
  • 94
  • 125
  • You're not using the full sed example given in my answer. I've tested it and works for me. – zaf Jun 02 '10 at 09:40

2 Answers2

6

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

4.3. How do I change only the first occurrence of a pattern?

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

Where LHS=this and RHS=that for your example.

If you know the pattern won't occur on the first line, omit the first -e and the statement following it.

zaf
  • 22,776
  • 12
  • 65
  • 95
1

sed by itself applies the edit thru out the file and combined with "g" flag the edit is applied to all the occurrences on the same line.

e.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 's/this/that/g' file.txt

  first line
  that  that <-- Both occurrences of "this" have changed
  that 
  that
  that
Ruchi
  • 679
  • 3
  • 13