string - 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?
解决方案
例如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
推荐阅读
- java - 如何测试应用程序与 Google Cloud Storage 的集成?
- haskell - 了解haskell中的循环/递归数据类型
- html - 使用纯 CSS 的出现和消失动画
- function - 将 GeoJSON 中的子字符串替换为弹出窗口传单
- c++ - cblas_dcopy 对 memcpy_s 和 std::copy 的影响如何?
- google-cloud-platform - 需要帮助:NodeJs 应用部署在 Google Cloud Run 上,无法连接到 Google Cloud SQL 实例
- sql - 错误:频谱嵌套查询错误。引用嵌套表的子查询不能包含 DISTINCT 操作。红移
- java - MSAL4J - 令牌生成错误:未知或无效实例
- python - Bokeh Server:点击 Scatter 以在条形图中显示其他数据
- python - 从 Python 调用 Go 字符串返回函数