2

I want to replace a string 'abc' with 'xyz', but there are other strings also contains 'abc', for example, 'abcdef'. I want to only replace exact match of 'abc', not 'abc' in 'abcef'. How would I accomplish that in linux?

Thanks!

aa51
  • 75
  • 1
  • 9

2 Answers2

2

You need to use "exact matches". For example, using a simple search and replace via sed generates behaviour you don't want:

Code Listing (Faulty Case)

echo "abc abcd abcdef" | sed 's/abc/xyz/g'

Example (Faulty Case)

xyz xyzd xyzdef


However, if you wrap your search query with < > chevrons (they need to be escaped with a backslash), you're good to go:

Code (Working Case)

echo "abc abcd abcdef" | sed 's/\<abc\>/xyz/g'

Example (Working Case)

xyz abcd abcdef
Cloud
  • 18,753
  • 15
  • 79
  • 153
0

You can accomplish what you want using the line end limiting character $. Example:

$ echo abcdef | sed -e 's/abc$/.../'
abcdef

$ echo abc | sed -e 's/abc$/.../'
...

Which will only match abc without any following characters. (it will however match 123abc). To further limit the match to only the string abc alone use the above in combination with the beginning of line character ^:

$ echo abcdef | sed -e 's/^abc$/.../'
abcdef

$ echo abc | sed -e 's/^abc$/.../'
...

$ echo 123abc | sed -e 's/^abc$/.../'
123abc

Using both the line begin and line end limiting characters, you can limit substitution to only abc.

If your shell is bash and you would like to use the builtin =~ operator to test against the regular expression in a script, without relying on external tools like sed, then you can accomplish the same thing in the following way:

#!/bin/bash

s1=${1:-abcdef}
pat=${2:-abc}
rep=${3:-...}

printf "\n string: %s  pattern: %s  replacement: %s\n" $s1 $pat $rep

[[ $s1 =~ ^${pat}$ ]] && s1=${s1/$pat/$rep}

printf "\n final string: %s\n\n" $s1

exit 0

Output

$ bash strpatrep.sh

 string: abcdef  pattern: abc  replacement: ...

 final string: abcdef

$ bash strpatrep.sh abc

 string: abc  pattern: abc  replacement: ...

 final string: ...

$ bash strpatrep.sh 123abc

 string: 123abc  pattern: abc  replacement: ...

 final string: 123abc
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85