使用python脚本实现基于指定字符串的文本排序

 

朋友用ansible导出了一个文件,文件中包含上千台机器的磁盘信息,他想要知道哪些机器最需要赶紧扩磁盘。思路是,按剩余磁盘空间百分数,从小到大对文本内容重新排序。下面是具体实现。

源文件ip.txt的格式是这样的:

10.1.2.1 224 | success | rc=0 >>
/dev/sda1  1.1T  28G  982G  3%  /export

10.1.2.1 24 | success | rc=0 >>
/dev/sda2  1.6T  15G  1.5T  1%  /export

下面是.py文件。运行这个python脚本后,可以生成ip_sorted.txt文件,是经过重排的文件,磁盘剩余空间越小,其机器信息会排在越前面。

#!/bin/bash
# -*- coding:utf-8 -*-

import os
import collections

with open('ip.txt','r') as f:
    file_dic_ip = {}
    file_dic_info = {}
    i = 0
    for line in f:
        count = int(os.popen("grep -c '^/dev' ip.txt").read())
        while i < count:
            lines_ip = os.popen("grep -v '^/dev' ip.txt | grep -v '^$' ").read().split('\n')
            lines_info = os.popen("grep -n '^/dev' ip.txt | awk -F ':' '{print $2}'").read().split('\n')
            file_dic_ip[lines_info[i]] = lines_ip[i]
            lines_info_percent = os.popen("grep -n '^/dev' ip.txt | awk -F ' ' '{print $5}'").read().split('%\n')
            file_dic_info[lines_info_percent[i]] = lines_info[i]
            i += 1

od = collections.OrderedDict(sorted(file_dic_info.items()))
with open('ip_sorted.txt','w') as f:
    for items in od.items():
        f.write(file_dic_ip[items[1]] + '\n' + items[1] + '\n\n')

流程图不太对,将就看看文字讲解吧

posted on 2016-08-12 22:25 kayegao 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/huamingao/p/5766788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值