Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete specified lines in a text file

Status
Not open for further replies.

NickC111

Technical User
Sep 23, 2010
44
GB
I want to delete specific lines in a text file that contains certain text.

I have a file called ‘TEST.txt’ located at C:\ this is my input file and it contains the following text as example

12122121131
TEST54545
8899665
2887566666
REMOVE45454
757574587485

When I specific ‘TEST’ & ‘REMOVE’ it finds the text in that row and deletes the entire row where the text is specified.

Afterwards

12122121131
8899665
2887566666
757574587485

It then outputs to the same file name
 
you need to:

+ open existing file
+ read existing file (you could do it line by line)
+ manipulate the stuff you have read in memory
+ write to the new file
+ close both old and new files
+ rename old to archive?
+ rename new to old

or

+ open existing file
+ read entire contents of existing file into memory
+ manipulate the stuff you have read in memory
+ close existing file
+ overwrite existing file with what is in memory

 
This will do it.

Code:
'open the file system object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WSHShell = CreateObject("Wscript.Shell")
'open the data file
Set oTextStream = objFSO.OpenTextFile("C:\Temp\Test.txt")
'make an array from the data file
FileContents = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close
Report = ""

For Each Line In FileContents
	If InStr(Line,"TEST") > 0 Or InStr(Line,"REMOVE") > 0 Then
		Report = Report
	Else
		If Len(Report) = 0 Then
			Report = Line
		Else
			Report = Report & vbCrLf & Line
		End If
	End If
Next

Set oTextStream = objFSO.CreateTextFile("C:\Temp\Test.txt")
oTextStream.Write Report
oTextStream.Close

I hope that helps.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top