首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将重复字重命名为dup,dup(1),dup(2)

如何将重复字重命名为dup,dup(1),dup(2)
EN

Stack Overflow用户
提问于 2020-10-19 13:55:56
回答 1查看 34关注 0票数 0

我有一个类似lisp,pascal,lisp,bash,bash,bash,lisp的字符串

我想要的结果是lisp, pascal,lisp(1), bash,bash(1),bash(2),lisp(2)

我的批准-

代码语言:javascript
复制
# 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  

我不太懂巴什所以我需要帮助..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-19 14:51:14

我会:

代码语言:javascript
复制
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

将产出:

代码语言:javascript
复制
declare -a output=([0]="lisp" [1]="pascal" [2]="lisp(1)" [3]="bash" [4]="bash(1)" [5]="bash(2)" [6]="lisp(2)")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64428861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档