Reputation: 11
I have a string "st xxx street st st" and i want to change to "street xxx street street street". I can replace middle st, but how can i replace others. Here is my code so far:
#!/bin/bash
SPACE=" "
input="st xxx street st st"
search_string="st"
replace_string="street"
output=${input//$SPACE$search_string$SPACE/$SPACE$replace_string$SPACE}
Upvotes: 0
Views: 98
Reputation: 108
I'm assuming that there are never any occurrences of street
at line beginning or end.
I suggest you try this:
Make all street
occurrences to st
:
output=${input//$SPACE$replace_string$SPACE/$SPACE$search_string$SPACE}
Now you can safely change st
to street
without the spaces:
output2=${output//$search_string/$replace_string}
Upvotes: 2
Reputation: 7277
Add this two
output=${output//$search_string$SPACE/$replace_string$SPACE}
output=${output//$SPACE$search_string/$SPACE$replace_string}
Update on comment, then with help of |
output="|${input//$SPACE$search_string$SPACE/$SPACE$replace_string$SPACE}|"
output=${output//"|$search_string$SPACE"/$replace_string$SPACE}
output=${output//"$SPACE$search_string|"/$SPACE$replace_string}
output=${output//|}
Or like Markante Makrele suggested
output=${input//$replace_string/$search_string}
output=${output//$search_string/$replace_string}
But better use sed.
Upvotes: 0
Reputation: 53
I have tried a 'simple-stupid' procedure, in which I first change all spaces to newlines, then search for (temporary) lines containing just 'st', which I change to street, and I revert the newlines back in the end.
input='anst xxx street st st'
echo "$input" | sed 's/ /\n/g' | sed 's/^st$/street/g' | tr '\n' ' ' | sed 's/ $/\n/'
output:
anst xxx street street street
Words only containing st shall not be substitued.
Upvotes: 0
Reputation: 2337
Try using sed
if that is possible:
echo "$input" | sed 's/\bst\b/street/g'
\b
in GNU sed
refers to word boundaries.
Also refer: How can I find and replace only if a match forms a whole word?
Upvotes: 3