2011-03-01 94 views
1

我需要shell腳本來獲取文本文件中的隨機未知垃圾文本。我被困在如何做到這一點,因爲我不知道垃圾文本會說什麼。基本上我需要刪除之前,之後和之間的一切。我想保留片段內的文字。Shell腳本刪除字符串前後的文本

--Begin file 


random unknown junk text 

----Begin Piece one ---- 
random important text 
----End Piece one ---- 

random unknown junk text 

----Begin Piece two ---- 
random important text 
----End Piece two ---- 

random unknown junk text 

----Begin Piece two ---- 
random important text 
----End Piece two ---- 

random unknown junk text 


end of file 

回答

2
sed -n '/^\(--Begin file\|end of file\)/{p;b}; /^----Begin Piece/{p;:a;n;/^----End Piece/{p;b};p;ba}' inputfile 

說明:

  • /^\(--Begin file\|end of file\)/{p;b} - 打印文件開始/結束線(匹配文字文本)
  • /^----Begin Piece/{ - 如果線塊匹配開始標記
    • p - 打印它
    • :a - 標註
    • n - 讀取下一行
    • /^----End Piece/{ - 如果它是塊結束標誌
      • p - 打印它
      • b - 科來結束閱讀輸入的下一行
    • } - 結束如果
    • p - 打印線區塊內的
    • ba - 科來標註,看是否有更多的線路中的塊
  • } - 如果最終
+0

這可行,但如何將它保存到同一個輸入文件? – Matt

+0

@Matt:'sed -n -i ...'(有些版本的'sed','-i'的備份擴展參數是強制的:'sed -n -i .bak ...')。你也可以執行'sed ... inputfile> temp && mv temp inputfile'。 –

+0

真棒,這有效,謝謝你的幫助。這是我第一次使用sed。 – Matt

0
#!/bin/bash 
exec 3< file.txt 
fl=0 
regex='----Begin Piece.+' 
regexe='----End Piece.+' 
while read <&3 
do 
    if [ $fl -eq 1 ] && [[ ! "$REPLY" =~ $regexe ]]; then 
     echo "$REPLY" 
    fi 
    if [[ "$REPLY" =~ $regex ]]; then fl=1; fi 
    if [[ "$REPLY" =~ $regexe ]]; then fl=0; fi 
done 
exec 3>&- 
+0

如果引用模式在'=〜'的右邊,它不再是一個正則表達式,而是從字面上理解。 –

+0

謝謝,我已經調試了代碼,現在沒關係。 – vissi

相關問題