2009-01-09 48 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);