Solved VB Script to delete all lines except the first line

April 19, 2016 at 23:29:10
Specs: Windows 7
Please assist. I would like to delete all the lines in text file except the first line...

Example:

Content of source file:
xxxxxxxxxxxxxxxxx
yyyyyyyyyyyyyyyy
uuuuuuuuuuuuuu
22222222222222

Result:
xxxxxxxxxxxxxxxxx


Thanks
RT


See More: VB Script to delete all lines except the first line

Report •


#1
April 20, 2016 at 01:00:48
✔ Best Answer
Here is a vbs (vb script) solution. What it does is,

Opens the file you specify for reading
Reads the first line
Store that line in a variable
Closes the file
Reopens the file for writing
Writes the line you stored in the variable replacing all other text
Saves
Closes

Dim iFile
Dim iLine
Dim FSO
Dim F
    
iFile = "C:\FileName.txt"
    
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(ifile)

iline =  f.readline

f.close

set f = FSO.OpenTextFile(iFile,2)

f.Write iline

f.close


Report •

#2
April 20, 2016 at 17:31:12
Thank you so much..The script worked perfectly.

Report •

#3
April 20, 2016 at 22:36:52
Seems like much todo to do not much.


@for /f "tokens=*" %%i in (myfile) do > newfile echo.%%i & goto :eof

=====================

M2 Get custom script or take private lessons


Report •

Related Solutions

#4
April 21, 2016 at 01:21:02
Hi Mechanix,

I have absolutely no experience or knowledge of batch, so was wondering if you could explain how I can run this code please?

What I have done is

1) Put the code in notepad and saved as 'abc.bat'
2) Created a text file in the same directory called 'Words.txt' which contains

A
B
C
D
E

I ran the code but it didn't modify the text file, so I

3) changed the

(myfile)
to
("Words.txt")

but nothing seems to happen, what am I doing wrong here?

Thanks,


Report •

#5
April 21, 2016 at 07:38:38
So close...

Remove the quotes from ("Words.txt")

Or rename Words.txt myfile

=====================

M2 Get custom script or take private lessons


Report •

#6
April 21, 2016 at 08:52:52
Hmmm still doing something wrong, i used your code as is without modification and in the same directory had

Myfile.txt
Myfile

But neither was modified, i think i need to learn some batch

Is it meant to output a new file?

> newfile
Suggests to me that you are trying to output to a new file?

Will do some reading i feel lame


Report •

#7
April 21, 2016 at 20:50:00
Yes, it makes a new file.

Keep plugging, that's how you learn.

=====================

M2 Get custom script or take private lessons


Report •

Ask Question