我有一个类似lisp,pascal,lisp,bash,bash,bash,lisp的字符串
我想要的结果是lisp, pascal,lisp(1), bash,bash(1),bash(2),lisp(2)
我的批准-
# converting string to array
string="lisp,pascal,lisp,bash,bash,bash,lisp"
set -f
array=(${string//,/ })
for i in "${!array[@]}"
do
echo "$i=>${array[i]}"
done 我不太懂巴什所以我需要帮助..。
发布于 2020-10-19 14:51:14
我会:
string="lisp,pascal,lisp,bash,bash,bash,lisp"
array=(${string//,/ })
output=()
for i in "${array[@]}"; do
# if the element already exists in the array
if ! printf "%s\n" "${output[@]}" | grep -Fxq "$i"; then
output+=("$i")
else
# extract the last number of that element
if
last_num=$(
printf "%s\n" "${output[@]}" |
sed '/'"$i"'(\([0-9]\{1,\}\))$/!d; s//\1/'
) && [[ -n "$last_num" ]]
then
# increment it and output
output+=("$i($((last_num+1)))")
else
# start with (1)
output+=("$i(1)")
fi
fi
done
declare -p output将产出:
declare -a output=([0]="lisp" [1]="pascal" [2]="lisp(1)" [3]="bash" [4]="bash(1)" [5]="bash(2)" [6]="lisp(2)")https://stackoverflow.com/questions/64428861
复制相似问题