Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Say there is a text file as below:

Hello world
types=""
Mario
types="Game"

All I want to do is find the first occurrence of type="" and append with word program

My desired output:

Hello world
types="program"
Mario
types="Game"

I Need to use in Unix shell scripting.

What I tried:

sed -i  '1,/types=\"\"/s/types=\"\"/types=\"program\"/' filename

This command only inserting and not appending. Tried adding a\ but still not working.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

POSIXly:

$ sed -e '1,/types=""/{
  //s/"/&program/
}
' file

It's strange that above fail on GNU sed, you need:

$ sed -e '1,/types=""/{
  /types=""/s/"/&program/
}
' file

All above fail if types="" appear at the first line. In that case, you can use GNU sed or BSD sed 0,/pattern/:

$ sed -e '0,/types=""/{                
  /types=""/s/"/&program/
}
' file

or POSIX one:

$ sed -e '/types=""/{
  s/"/&program/
  :1
  n
  b1
}
' file

or see @mikeserv's answer.

share|improve this answer
    
I get this error {sed: -e expression #1, char 0: no previous regular expression} –  VRVigneshwara 2 days ago
    
@VRVigneshwara: What's your sed version? you need to use the second if you use GNU sed. –  cuonglm 2 days ago
1  
1,/types=""/ doesn't work if types="" is on the first line (that is, sed starts looking for types="" from the second line, and thus you get the first two types="" replaced). A solution is to use 0,/types=""/, but the 0 address is not accepted by all seds. It's ok for GNU sed, and for *BSD sed though. –  lcd047 2 days ago
    
@lcd047: Good point. Updated! –  cuonglm 2 days ago
    
@cuonglm Last one aced it ! but it's printing below after executing the command . How can it be avoided? –  VRVigneshwara yesterday
{   sed '/types=""/!b
        s/"/&program/;q'
    cat
}   <infile >outfile

A POSIX sed will leave its input file offset exactly where it quits input. With GNU sed you might need the -u option, though.

share|improve this answer

You can use i to insert, then d to delete the line, and q to quit:

~$ sed '/types=""/{i\
> types="program"
> d;q}' f
Hello world
types="program"
Mario
types="Game"

The following doesn't work (thanks @mikeserv): or simply c to change the line, and q to quit:

~$ sed '/types=""/{c\
> types="program"
> q}' f
Hello world
types="program"
Mario
types="Game"

(and of course keep the -i for in place)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.