Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bashshell脚本中,如何在重复行的末尾追加一个数字?_Bash_Shell_Loops_Scripting - Fatal编程技术网

在bashshell脚本中,如何在重复行的末尾追加一个数字?

在bashshell脚本中,如何在重复行的末尾追加一个数字?,bash,shell,loops,scripting,Bash,Shell,Loops,Scripting,如果我有一个包含以下行的文件: orange apple mango orange mango orange 如何在每个重复行中添加一个数字以获得: orange apple mango orange 2 mango 2 orange 3 使用bash脚本?提前感谢您,我对编写脚本还不熟悉。纯bash解决方案:使用关联数组 #!/bin/bash declare -A seen while read line ; do if ((seen[$line]++)) ; then

如果我有一个包含以下行的文件:

orange
apple
mango
orange
mango
orange
如何在每个重复行中添加一个数字以获得:

orange
apple
mango
orange 2
mango 2
orange 3

使用bash脚本?提前感谢您,我对编写脚本还不熟悉。

纯bash解决方案:使用关联数组

#!/bin/bash

declare -A seen
while read line ; do
    if ((seen[$line]++)) ; then
        echo "$line ${seen[$line]}"
    else
        echo "$line"
    fi
done
或者,使用Perl:

perl -pe '$seen{$_}++ and s/$/ $seen{$_}/'
  • -p
    逐行读取输入并在处理后打印
  • hash
    %seen
    保留字符串被看到的次数。如果第一次没有看到,当
    ++
    运算符返回false时,该数字将追加到要打印的行

您尝试过什么?怎么会失败?谢谢!如何将其附加到文件中,而不是使用echo打印出来?将输出重定向到新文件,将新文件重命名为旧名称。