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
3
  • 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' Commented May 8, 2019 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
    Commented May 8, 2019 at 15:06
  • Hi Philippos, I want to rename only php rather than other strings Commented May 13, 2019 at 9:04

2 Answers 2

0

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

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

Another way of word boundary :

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .