Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

sed

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
like image 605
webminal.org Avatar asked Jun 02 '10 09:06

webminal.org


People also ask

What is g at the end of sed command?

The g character at the end of the s subcommand tells the sed command to make as many substitutions as possible on each line. Without the g character, the sed command replaces only the first occurrence of the word happy on a line. The sed command operates as a filter.

What is g in sed?

The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced. The regular expression (i.e. pattern) to be searched is placed after the first delimiting symbol (slash here) and the replacement follows the second symbol.

What does sed s do?

Its basic concept is simple: the s command attempts to match the pattern space against the supplied regular expression regexp ; if the match is successful, then that portion of the pattern space which was matched is replaced with replacement . For details about regexp syntax see Regular Expression Addresses.

What is D in SED?

'd' in sed means delete, 'p' for print. These are mainly used while searching for regex in pattern space.


2 Answers

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.

like image 150
zaf Avatar answered Nov 02 '22 19:11

zaf


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
like image 1
Ruchi Avatar answered Nov 02 '22 18:11

Ruchi