首页 > 解决方案 > Delete common values from string variables using shell script

问题描述

I want to delete duplicate values from a string/s. (I am NOT looking for a common solution that suits for both the examples.)

Example 1:

var1="foo bar foo1 foo2 foo bar"

Expected output:

var1="foo1 foo2"

Example 2:

var1="foo bar foo1 foo2"
var2="foo bar"

Expected output:

var1="foo1 foo2"

I had tried the following echo $var1 | tr ' ' '\n' | sort | uniq

This gives me the values foo and bar along with foo1 and bar1

Any thoughts?

标签: stringbashshellvariables

解决方案


例如1,请尝试:

var1="foo bar foo1 foo2 foo bar"
declare -A seen         # count the occurrences of the words in var1
declare -a result

for i in $var1; do
    (( seen[$i]++ ))    # increment the counter of the word
done

for i in "${!seen[@]}"; do
    if (( ${seen[$i]} == 1 )); then
                        # if the word occurs just once
        result+=($i)    # then append the word to the result
    fi
done
echo "${result[*]}"

输出:

foo1 foo2

作为示例2:

var1="foo bar foo1 foo2"
var2="foo bar"
declare -A seen         # count the occurrences of the words in var2
declare -a result

for i in $var2; do
    (( seen[$i]++ ))
done

for i in $var1; do
    if ! (( ${seen[$i]} )); then
                        # if not found in var2 list
        result+=($i)    # then append the word to the result
    fi
done
echo "${result[*]}"

输出:

foo1 foo2

推荐阅读