I have a string as follows:

/test/test/ 12 /test/test

My goal is to turn it into:

/test/est/ 12 /test/test

This is the command:

echo "$x" | sed 's@\(/*/\).@\1@g'"

I am using at the moment but it is applying it everywhere instead of at the second instance of "/"

  • could you please update your post and show us what is your string and what you want as a result ? Its unclear.
    – Rahul
    Apr 27 '16 at 12:18
  • g means global - everywhere
    – Jeff Schaller
    Apr 27 '16 at 12:22
  • If you have GNU sed, you can replace just the nth match explicitly e.g. sed 's@/.@/@2' Apr 27 '16 at 12:24

As stated by steeldriver, if you use GNU sed, you can tell which occurrence should be replaced, e.g.:

echo "/test/test/ 12 /test/test" | sed -n -e  's_/._/_2 p' 

If you can not make use of this feature you can also write:

echo "/test/test/ 12 /test/test" | sed -n -r -e  's_(/[a-z]([a-z]+))\1_\1/\2_ p'

Biliography: http://www.grymoire.com/Unix/Sed.html [Using \1 to keep part of the pattern]

echo "/test/test/ 12 /test/test" | sed 's/\/test\/t/\/test\//'

Nice and easy...

sed -n "s/test/est/2p"
  • -n don't print anything
  • s/ substitute
  • "test" with "est"
  • /2 but only the second instance
  • p print the results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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