2012-03-20 45 views
2

需要使用bash腳本或python腳本來查找和替換兩個標籤之間的文本?查找和替換POM中兩個單詞之間的內容

E.g:

<start>text to find and replace with the one I give as input<end> 

「文本發現,並與一個我給輸入替換」僅僅是一個例子,它可以改變每一次。

我要像做./changetxt inputfile.xxx newtext

其中changetxt有腳本; inputfile.xxx有需要改變文字和newtext就是進入inputfile.xxx

+0

行,就是更加清晰。我只需要知道你將如何確定要改變的文字。它總是在相同的標籤之間還是會有所不同? – RickyA 2012-03-21 09:15:46

+0

@RickyA - 它總是在相同的標籤 – user1164061 2012-03-21 16:15:25

回答

1

蟒蛇:

import sys 

if __name__ == "__main__": 
    #ajust these to your need 
    starttag = "<foo>" 
    endtag = "</foo>" 

    inputfilename = sys.argv[1] 
    outputfilename = inputfilename + ".out" 
    replacestr = sys.argv[2] 

    #open the inputfile from the first argument 
    inputfile = open(inputfilename, 'r') 
    #open an outputfile to put the result in 
    outputfile = open(outputfilename, 'w') 

    #test every line in the file for the starttag 
    for line in inputfile: 
     if starttag in line and endtag in line: 
      #compose a new line with the replaced string 
      newline = line[:line.find(starttag) + len(starttag)] + replacestr + line[line.find(endtag):] 
      #and write the new line to the outputfile 
      outputfile.write(newline) 
     else: 
      outputfile.write(line) 
    outputfile.close() 
    inputfile.close() 

這個保存在replacetext.py文件並運行爲蟒蛇replacetext.py \路徑\到\ inputfile中「我想要的標籤之間的這段文字」

+1

我不認爲這就是OP的含義。 。 。 – ruakh 2012-03-20 20:21:37

+0

「替換兩個標籤之間的文本」.. – 2012-03-20 20:22:40

+0

不,我也認爲他不是這個意思,但這是他要求的...... – RickyA 2012-03-20 20:27:41

0

您也可以使用BeautifulSoup這一點,從他們的文檔:

如果您設置一個標籤的.string屬性,日Ë標籤的內容被替換 用你給的字符串:

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>' 
soup = BeautifulSoup(markup) 

tag = soup.a 
tag.string = "New link text." 
tag 
# <a href="http://example.com/">New link text.</a> 
+0

是的,但這個例子不是HTML也不是XML – 2012-03-20 20:42:59

+0

@Niklas B - 優點:( – fraxel 2012-03-20 20:45:21

相關問題