Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have sed make substitute on string but SKIP first occurrence

Tags:

sed

I have been through the sed one liners but am still having trouble with my goal. I want to substitue matching strings on all but the first occurrence of a line. My exact usage would be:

 $ echo 'cd /Users/joeuser/bump bonding/initial trials' | sed <<MAGIC HAPPENS>
 cd /Users/joeuser/bump\ bonding/initial\ trials

The line replaced the space in bump bonding with the slash space bump\ bonding so that I can execute this line (since when the spaces aren't escaped I wouldn't be able to cd to it).

Update: I solved this by just using single quotes and outputting

 cd 'blah blah/thing/another space/'

and then using source to execute the command. But it didn't answer my question. I'm still curious though... how would you use sed to fix it?

like image 641
physicsmichael Avatar asked Jan 29 '10 23:01

physicsmichael


People also ask

How do you escape ampersand in sed?

\& works for me. For example, I can replace all instances of amp with & by using sed "s/amp/\&/g" . If you're still having problems, you should post a new question with your input string and your code. Yea it does.

How do I change the first occurrence in sed?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.

Which is the correct command to replace the first occurrence?

To replace the first occurrence of a character in Java, use the replaceFirst() method.


1 Answers

You can avoid the problem with g and n

Replace all of them, then undo the first one:

sed -e 's/ /\\ /g' -e 's/\\ / /1'

Here's another method which uses the t branch-if-substituted command:

sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'

which has the advantage of leaving existing backslash-space sequences in the input intact.

like image 68
Dennis Williamson Avatar answered Sep 19 '22 16:09

Dennis Williamson