Linux 中shell 实现给同一列中的不同类别从头编号

 

001、

[root@pc1 test02]# ls
a.txt
[root@pc1 test02]# cat a.txt                                         ## 准备一个测试数据
aa
aa
aa
bb
bb
cc
cc
cc
cc
dd
dd
dd
[root@pc1 test02]# awk '{ay[$1]++; print $0ay[$1]}' a.txt           ## 依据 aa、bb、cc、dd分别从头编号
aa1
aa2
aa3
bb1
bb2
cc1
cc2
cc3
cc4
dd1
dd2
dd3

 。

 

002、python实现

[root@pc1 test02]# ls
a.txt  test.py
[root@pc1 test02]# cat a.txt                 ## 测试数据
aa
aa
aa
bb
bb
cc
cc
cc
cc
dd
dd
dd
[root@pc1 test02]# cat test.py               ## python程序
#!/usr/bin python
# -*- coding: utf-8 -*-

import sys
import os

in_put = open("a.txt", "r")
out_put = open("result.txt", "w")

dict1 = {}

for i in in_put:
        i = i.strip()
        if i not in dict1:
                dict1[i] = 1
        else:
                dict1[i] += 1
        print(i + str(dict1[i]), file = out_put)

in_put.close()
out_put.close()
[root@pc1 test02]# python test.py                ## 执行程序
[root@pc1 test02]# ls
a.txt  result.txt  test.py
[root@pc1 test02]# cat result.txt                ## 运算结果
aa1
aa2
aa3
bb1
bb2
cc1
cc2
cc3
cc4
dd1
dd2
dd3

 

 

 。

 

posted @ 2024-01-15 00:08  小鲨鱼2018  阅读(24)  评论(0编辑  收藏  举报