This might work for you:
echo "afs=1;bgd=1;cgd=1;djh=1;fgjhh=1;" |
sed 's/^/\n/;:a;/\n\(djh=[0-9]*\);/s//\1,\n/;ta;s/\n\([^=]*\)=1;/\1,\n/;ta;s/.$//'
afs,bgd,cgd,djh=1,fgjhh,
Explanation:
This method uses a unique marker (\n
is a good choice because it cannot appear in the pattern space as it is used by sed as the line delimiter) as anchor for comparing throughout the input string. It is slow but can scale if more than one exception is needed.
- Place the marker in front of the string
s/^/\n/
- Name a loop label
:a
- Match the exception(s)
/\n\(djh=[0-9]*\)/
- If the exception occurs substitute as necessary. Also bump the marker along
/s//\1,\n/
- If the above is true break to loop label
ta
- Match the normal and substitute. Also bump the marker along
s/\n\([^=]*\)=1;/\1,\n/
- If the above is true break to loop label
ta
- All done remove the marker
s/.$//
or:
echo "afs=1;bgd=1;cgd=1;djh=1;fgjhh=1;" |
sed 's/\<djh=/\n/g;s/=[^;]*;/,/g;s/\n\([^;]*\);/djh=\1,/g'
afs,bgd,cgd,djh=1,fgjhh,
Explanation:
This is fast but does not scale for multiple exceptions:
- Globaly replace the exception string with a new line
s/\<djh=/\n/g
- Globaly replace the normal condition
s/=[^;]*;/,/g
- Globaly replace the
\n
by the exception string s/\n\([^;]*\);/djh=\1,/g
N.B. When replacing the exception string make sure that it begins on a word boundary \<