2013-04-26 69 views
3

我使用Python和同樣使用的egrep挑出某些線路,並創建與這些線.txt文件:避免寫什麼到文件

os.system('cat {0}|egrep " {1}."|egrep " 7..\."|egrep " 8..\." >> {2}_{1}_800.tim' .format(full,epoch,pname)) 

額外的一部分,我不知道如何做的是,如果沒有匹配的行,我不想要寫一個空白的.txt文件。

任何幫助將是偉大的,謝謝。

+6

你爲什麼不使用純粹的Python? – Kiro 2013-04-26 10:51:58

+1

如果你放置一個'||,會發生什麼rm {2} _ {1} _800.tim'在命令結尾? – mgilson 2013-04-26 10:53:03

回答

0

好的,如果我沒有弄錯,你可以使用一些if語句。

grep "my pattern" input-file.txt | { 
    FILE=output-file.txt 
    read x; #Read the first line 
    if ! [[ $x ]]; then 
    exit #If the 1st line was empty, then there is no match 
    fi 
    echo $x >> $FILE 
    while read line; do 
    echo $x 
    done >> $FILE 
} 

這應該工作得很好。現在,你可以寫這個

'cat {0}|egrep " {1}."|egrep " 7..\."|egrep " 8..\." | 'cat {0}|egrep " {1}."|egrep " 7..\." | egrep " 8..\." | { FILE={2}_{1}_800.tim; read x; if ! [[ $x ]]; then  exit; fi; echo $x >> $FILE; while read line; do  echo $x; done >> $FILE; }