1

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

Example:

str1=/home/username
str2=/home/username/project
str3=$str1+$str2

Result:

echo $str3
>> /home/username/project

How do i provided it like str3?

1
  • 1
    My thought is, the premise of your question is highly likely to be wrong. The fact that you want to do this means you probably already have gone off track. Then again, who knows, requirements are many and varied. Commented Jul 20, 2022 at 8:43

1 Answer 1

2

There is no built-in facility for this. If you know that str2 may or may not contain str1 as a prefix, you can exclude it with a parameter expansion:

str3=$str1${str2#"$str1"}

The quotes are necessary to guard against shell metacharacters in the pattern; for example, ${foo#*} removes everything from foo whereas ${foo#"*"} only removes a literal asterisk if present.

Sign up to request clarification or add additional context in comments.

2 Comments

Does this work if str1 may or may not contain str2, or does it only work if str2 may or may not contain str1? The original poster is asking a poor question, but taken literally it has to do both.
This is only for exactly the case in the first paragraph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.