views:

892

answers:

2

I have an ascii file and in there somewhere is the line: BEGIN and later on the line: END

I'd like to be able to remove those two lines and everything in between from a command line call in windows. This needs to be completely automated.

EDIT: See http://stackoverflow.com/questions/425864/sed-in-vista-how-to-delete-all-symbols-between for details on how to use sed to do this (cygwin has sed).

EDIT: I am finding that SED could be working but when I pipe the output to a file, the carriage returns have been removed. How can I keep these? Using this sed regex:

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

.. where the start section is 'GlobalSection(TeamFoundationVersionControl) = preSolution' and the end section is 'EndGlobalSection'. I'd also like to delete these lines as well.

EDIT: I am now using something simpler for sed:

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

The line feeds are still an issue though

+1  A: 

Alternately, what I use these days is a scripting language that plays nicely with windows like Ruby or Python for such tasks. Ruby is easy to install in windows and makes problems like this child's play.

Here's a script you could use like: 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)

This does a pretty good job, allows for a lot of flexiblity, and is possibly more readable than sed.

danieltalsky
+1  A: 

Here is a 1-line Perl command that does what you want (just type it from the Command Prompt window):

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

Carriage returns and line feeds will be preserved properly. The original version of myfile.txt will be saved as myfile.txt.bak.

If you don't have Perl installed, get ActivePerl.

j_random_hacker