简体   繁体   中英

Replace substring in shell script

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}

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?

I'm assuming that there are never any occurrences of street at line beginning or end.

I suggest you try this:

  1. Make all street occurrences to st :

     output=${input//$SPACE$replace_string$SPACE/$SPACE$search_string$SPACE}
  2. Now you can safely change st to street without the spaces:

     output2=${output//$search_string/$replace_string}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM