0

I want to replace string in file using sed/grep but the string is mingled with another strings

Example:

sed -i 's/php/vinu/g' test.yml  # to replace string php with vinu

test.yml

php
phpehealth
dophp
testingphpin

In the above yml file contains multiple "php" strings, but I want to replace only "php" string with "vinu" and rest should not touch.

expected o/p:

vinu
phpehealth
dophp
testingphpin
  • Maybe because you are using the /g flag. Remove the /g flag and it will work beatifully for you. Also if your string always starts with php then consider `/^php/vinu/g' – Valentin Bajrami May 8 at 6:55
  • What about line with php inside? Should the php get replaced here? (The given answers would do so) Or do you only want to replace a php in a line of it's own? (Then try s/^php$/vinu/) – Philippos May 8 at 15:06
  • Hi Philippos, I want to rename only php rather than other strings – Kandikuppa Vinod May 13 at 9:04
0

Use word boundaries in the regular expression if your version of sed supports them, e.g.

sed -i 's/\<php\>/vinu/g' 
  • Thank you very much. It is working. – Kandikuppa Vinod May 8 at 6:56
  • I think the command should be sed -i 's/\<php\>/vinu/g'. You missed single quote before substitute – Kandikuppa Vinod May 8 at 6:59
  • Note that this will only work with GNU sed – Philippos May 8 at 15:03
0

Another way of word boundary :

sed -i 's/\bphp\b/vinu/g' file
  • Note that this will only work with GNU sed – Philippos May 8 at 15:03

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.