Combine two strings and remove duplicate characters

I have 2 strings and I want to combine them and remove duplicates.

Example:

a=abcdefghijkl
b=dfg 

then combining them should yield

c=dfgabcehijkl

where the value of b is provided by the user. How can I do this?

Upvotes: 1

Views: 887

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74595

No need for sed. You can do this in pure bash:

a=abcdefghijkl
b=dfg
c="$b${a//[$b]/}"
echo "$c"

This uses the built-in string substitution capabilities of bash to do a global replacement on $a, removing all characters that are in $b. Output:

dfgabcehijkl

Upvotes: 4

Zilicon
Zilicon

Reputation: 3860

c="${b}$(echo "${a}" | sed "s/[${b}]//g")"

Upvotes: 4

Related Questions