tags:

views:

76

answers:

2

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
+5  A: 

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
please check my example above.
lakshmipathi
You're not using the full sed example I've tested it and works for me.
zaf
thanks using -e works - sed -e '1s/LHS/RHS/;t' -e '1,/LHS/s//RHS/'
lakshmipathi
A: 

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