2009-01-09 47 views
2

我有一個ASCII文件,並在那裏的地方刪除文本行: BEGIN 後來就行了: ENDWindows命令來檢測和文件

我希望能夠刪除這兩行代碼以及窗口中的命令行調用之間的所有內容。這需要完全自動化。

編輯:請參閱sed in Vista - how to delete all symbols between?瞭解如何使用sed來執行此操作(cygwin有sed)的詳細信息。

編輯:我發現SED可以工作,但是當我管輸出到一個文件,回車已被刪除。我怎樣才能保持這些?使用這個sed的正則表達式:!

/^ GlobalSection(TeamFoundationVersionControl)= preSolution $ /,/^EndGlobalSection $/{ /^ GlobalSection(TeamFoundationVersionControl)= preSolution $/{ /^ EndGlobalSection $/D } }

..其中開始部分是'GlobalSection(TeamFoundationVersionControl)= preSolution',結束部分是'EndGlobalSection'。我也想刪除這些行。

編輯:我現在用更簡單的東西了sed的:

/^ GlobalSection(TeamFoundationVersionControl)= preSolution $ /,/^EndGlobalSection $/d

的換行符仍然雖然

問題
+0

如果回答您剛纔的問題是不能令人滿意的,然後這樣說。這個新問題是相同的。 http://stackoverflow.com/questions/425864/sed-in-vista-how-to-delete-all-symbols-between – 2009-01-09 00:20:48

回答

1

或者,我現在使用的是一種腳本語言,可以很好地與諸如Ruby或Python這樣的窗口一起玩這樣的任務。 Ruby很容易在Windows中安裝,並且會造成類似這種兒童遊戲的問題。

這裏有一個腳本,你可以使用這樣的: cutBeginEnd.rb myFileName.txt

sourcefile = File.open(ARGV[0]) 

# Get the string and do a multiline replace 
fileString = sourceFile.read() 
slicedString = fileString.gsub(/BEGIN.*END\n/m,"") 

#Overwrite the file 
sourcefile.pos = 0     
sourcefile.print slicedString    
sourcefile.truncate(f.pos) 

這做了很好的工作,使得很多flexiblity的,而且可能是更具可讀性比sed的。

1

這裏是一個1行的Perl命令,做你想要的(剛剛從命令提示符窗口中鍵入):

perl -i.bak -ne "print unless /^BEGIN\r?\n/ .. /^END\r?\n/" myfile.txt 

回車和換行符將被妥善保存。 myfile.txt的原始版本將保存爲myfile.txt.bak

如果您沒有安裝Perl,請獲取ActivePerl

0

下面介紹如何使用C#正則表達式來刪除整個GlobalSection(TeamFoundationVersionControl)= preSolution部分:

// Create a regex to match against an entire GlobalSection(TeamFoundationVersionControl) section so that it can be removed (including preceding and trailing whitespace). 
// The symbols *, +, and ? are greedy by default and will match everything until the LAST occurrence of EndGlobalSection, so we must use their non-greedy counterparts, *?, +?, and ??. 
// Example of string to match against: " GlobalSection(TeamFoundationVersionControl) ...... EndGlobalSection  " 
Regex _regex = new Regex(@"(?i:\s*?GlobalSection\(TeamFoundationVersionControl\)(?:.|\n)*?EndGlobalSection\s*?)", RegexOptions.Compiled);