2014-04-02 2 views
0

텍스트의 서식을 변경해야합니다.명령 출력의 형식 변경

Filesystem   Size Used Avail Use% Mounted on 
/dev/sda3    20G 15G 4.2G 78%/
/dev/sda6    68G 39G 26G 61% /u01 
/dev/sda2    30G 5.8G 22G 21% /opt 
/dev/sda1    99M 19M 76M 20% /boot 
tmpfs     48G 8.2G 39G 18% /dev/shm 
/dev/mapper/vg3-KPGBKUP4 
       10T 7.6T 2.5T 76% /KPGBKUP4 

나는 아래와 같은 출력을 원하는 :

20G 15G 4.2G 78% 
68G 39G 26G 61% 
30G 5.8G 22G 21% 
99M 19M 76M 20% 
48G 8.2G 39G 18% 
10T 7.6T 2.5T 76% 

이 내가 한 일이지만,이 내 스크립트에서 모든 파티션의 이름을 넣어달라고 요구한다. 이 스크립트는 다른 이름의 파티션이있는 25 개 이상의 서버에서 실행해야하며 계속 변경됩니다. 더 좋은 방법이 있습니까?

import os, sys, fileinput 
for line in fileinput.input('report.txt', inplace= True): 
    line = line.replace("/dev/sda3    ", "") 
    line = line.replace("/dev/sda6    ", "") 
    line = line.replace("/dev/sda2    ", "") 
    line = line.replace("/dev/sda1    ", "") 
    line = line.replace("tmpfs     ", "") 
    line = line.replace("/dev/mapper/vg3-KPGBKUP4", "") 
    line = line.replace("/KPGBKUP4", "") 
    line = line.lstrip() 
    sys.stdout.write(line) 
+2

[AWK] (http://en.wikipedia.org/wiki/AWK)에 대해 들어 본 적이 있습니까? – filmor

+1

도움이 된 답변이 있으면 수락 된 것으로 표시하십시오. – bosnjak

답변

0

여기에 신속하고 더러운 솔루션입니다 :

이 내 현재 스크립트입니다

first = True 
for line in open('A.py'): 
    # Skip the header row 
    if first: 
     first = False 
     continue 
    # For skipping improperly formatted lines, like the last one 
    if len(line.split()) == 6: 
     filesystem, size, used, avail, use, mount = line.split() 
     print size, used, avail, use 
+0

OP의 예와 같이 결과물이 오른쪽 정렬 된 결과물이 아니며 행의 항목이 여러 공백으로 구분된다는 사실도 처리하지 않습니다. –

1

당신이 사용할 수있는 정규식 :

import os, sys, fileinput 
import re 

for line in fileinput.input('report.txt', inplace= True): 
    sys.stdout.write(re.sub('^.+?\s+','', line.strip())) 

파일의 차례 나오는이있는 경우

당신의 첫 번째 예에서와 같이, 줄이 실제 줄 바꿈 문자에 의해 두 줄로 분리되었을 때, 당신은 변수에 전체 파일을 읽고, 그리고 sub() 기능에 flags=re.MULTILINE를 사용해야합니다

f = open('report.txt', 'r') 
print re.sub('^.+?\s+','',a,flags=re.MULTILINE) 
1

당신이 이런 식으로 뭔가를 시도 했습니까?

import os, sys, fileinput 
for line in fileinput.input('report.txt'): 
    line = line.split() 
    print ' '.join(line[1:]) 
-1
print ' '.join(line.split()[1:5]) 
이 사용자가 제공 한 입력을 작동
+0

이 질문에 대한 답변을 제공하지 않습니다. 비평하거나 저자의 설명을 요청하려면 게시물 아래에 의견을 남겨 둡니다. – Rico

+0

Rico - 답변을 제공해 주었고 적절한 형식으로 파싱하고 싶었습니다. 이미 forloop을 사용하고 있습니다. 필요한 형식으로 출력 형식을 지정하는 줄을 제공했습니다. – onsy

+0

자세히 설명해 주시겠습니까? 단 한 줄의 대답이 아니라 ... – Rico

1

:

for line in open('report.txt'): 
    if line.startswith('Filesystem'): 
     # Skip header line 
     continue 
    try: 
     part, size, used, avail, used_percent, mount = line.split(None) 
    except ValueError: 
     # Unexpected line format, skip 
     continue 

    print ' '.join([size, 
        used.rjust(5), 
        avail.rjust(5), 
        used_percent.rjust(5)]) 

여기에서 중요한 점은 연속적인 공백에 분할하기 위해 line.split(None)을 사용하는 것입니다 -이에 대한 자세한 내용은 split()`에 문서를 참조 행동.

문자열을 오른쪽 정렬하도록 형식을 지정하는 방법에 대해서도 str.rjust()을 참조하십시오.

1
#!/usr/bin/env python                        

import re, subprocess, shlex 

cmd = 'df -Th' 

# execute command 
output = subprocess.Popen(shlex.split(cmd), stdout = subprocess.PIPE) 
# read stdout-output from command 
output = output.communicate()[0] 
# concat line-continuations 
output = re.sub(r'\n\s+', ' ', output) 
# split output to list of lines 
output = output.splitlines()[1:] 

# print fields right-aligned in columns of width 6 
for line in output: 
    print("{2:>6}{3:>6}{4:>6}{5:>6}".format(*tuple(line.split()))) 

report.txt를 읽지 않고 df-Command를 실행하기 위해 subprocess를 사용합니다.

출력을 포맷하려면 비단뱀 Format String Syntax을 사용합니다.