sed: replace any number of occurrences of a certain pattern
Solution 1:
You want to use the /g switch at the end to parse more than one substitution per line.
sed s/--/X-X-X/g
Solution 2:
Edit:
Using your new requirement:
sed 's/\o47[^\o47]*\o47/\n&\n/g;:a;s/\(\n\o47[^\n]*\)--/\1X-X-X/;ta;s/\n//g' input file
Edit 2:
For some versions of sed
which don't like semicolons:
sed -e 's/\o47[^\o47]*\o47/\n&\n/g' -e ':a' -e 's/\(\n\o47[^\n]*\)--/\1X-X-X/' -e 'ta' -e 's/\n//g' inputfile
If your sed
also doesn't support octal escape codes:
sed -e "s/'[^']*'/\n&\n/g" -e ':a' -e "s/\(\n'[^\n]*\)--/\1X-X-X/" -e 'ta' -e 's/\n//g' inputfile
Original Answer:
You should usually use single quotes to surround the sed
script so you don't have to escape characters which may be special to the shell. Even though it's not necessary in this instance it's a good habit to develop.
sed 's/--/X-X-X/g' inputfile
or
var="hell --this -- world is --beaut--iful"
newvar=$(echo "$var" | sed 's/--/X-X-X/g')
Without the g
modifier, the replacement is performed on the first match on each line of input. When g
is used, each match on each line of input is replaced. You can also do the replacement for particular matches:
$ var="hell --this -- world is --beaut--iful"
$ echo "$var" | sed 's/--/X-X-X/2'
hell --this X-X-X world is --beaut--iful
Solution 3:
$ echo "hell --this -- world is --beaut--iful" | sed s"/--/X-X-X/g"
hell X-X-Xthis X-X-X world is X-X-XbeautX-X-Xiful
The key is the g
switch: It causes sed
to replace all occurrences.