PDA

View Full Version : Delete blank lines from a text file



G Mills
03-10-2005, 04:32 AM
Does anyone know if it is possible to remove blank lines from a text file?

I am trying to remove entries from a hosts file and can delete the entry but it leaves a blank line. I would like to remove the blank lines to keep the hosts file tidy - any ideas?

Worm
03-10-2005, 07:52 AM
I didn't test this code, but it should work, or at least with minimal changes



--read the host file into a table
tblHosts = TextFile.ReadToTable(_SystemFolder.."\\Drivers\\etc\\hosts")
--if the table isn't empty
if Table.Count(tbHosts) > 0 then
--start at the end of the file and loop through
--to remove all blank lines
for n=Table.Count(tblHosts), 1, -1 do
--trim spaces
sTemp = String.TrimLeft(tblHosts, " ")
if sTemp == "\r\n" then
Table.Remove(tblHosts, n)
end
end
end

G Mills
03-10-2005, 10:20 AM
Thanks for having a look at this but it doesn't seem to work. It fails at runtime with a message of "Argument 1 must be of type string".

I think this is on the sTemp = String.TrimLeft(tblHosts, " ") line as tblhosts should be a string.

Tried a few things but still stuck I'm afraid, any other ideas would be greatly appreciated.

Brett
03-10-2005, 10:21 AM
Make it:

sTemp = String.TrimLeft(tblHosts[n], " ")

Worm
03-10-2005, 10:25 AM
Also:

if Table.Count(tbHosts) > 0 then

should be

if Table.Count(tblHosts) > 0 then

<SelfReminder>Test Code before Posting</SelfReminder>

Worm
03-10-2005, 10:32 AM
Okay, I actually tested this one :)



--read the host file into a table
tblHosts = TextFile.ReadToTable(_SystemFolder.."\\Drivers\\etc\\hosts")
--if the table isn't empty
if Table.Count(tblHosts) > 0 then
--start at the end of the file and loop through
--to remove all blank lines
for n=Table.Count(tblHosts), 1, -1 do
--trim spaces
sTemp = String.TrimLeft(tblHosts[n], " ")
if sTemp == "" then
Table.Remove(tblHosts, n)
end
end
end

TextFile.WriteFromTable(_SystemFolder.."\\Drivers\\etc\\hosts", tblHosts, false)

Absynthe
03-11-2005, 12:18 AM
<SelfReminder>Test Code before Posting</SelfReminder>

Air code will get you every time.

That said it was an elegant solution :)

G Mills
03-11-2005, 03:44 AM
Sure is, tested this and it worked a treat! Thanks alot for all your help.

Worm
03-11-2005, 04:58 AM
Air code will get you every time.


Funny. My Air Guitar is so much better than the real deal, why not my code? Another of life's mysteries I guess.

Corey
03-11-2005, 05:04 AM
Air guitar is more noble than air coding by a factor of three. Just an observation...