开发者

sed 's/this/that/' -- ignoring g but still replace entire file

开发者 https://www.devze.com 2023-01-01 17:18 出处:网络
as title said, Im trying to change only the first occurrence of word.By using sed \'s/this/that/\' file.txt

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:

$ ca开发者_JAVA百科t 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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消