Using ColdFusion to remove a line from a file

I thought I would very quickly write a tutorial on how to remove a line from a file in ColdFusion, this was written and tested under ColdFusion 9. But the code should work under ColdFusion 8.

There is sometimes a need to remove lines from a file, and ColdFusion has made it very simple to do. The one thing to remember is that you can't do it within the current file, so the only real solution is to recreate the file with the missing information.

As you can see you could expand this code to rename the file on success, but for now I just want to show how simple it actually is.

<cfset lineToRemove = "ccccc" />
<cfscript>
   oldFile = FileOpen("#ExpandPath('test1.txt')#", "read");
   newFile = FileOpen("#ExpandPath('test2.txt')#", "write");
   while(NOT FileIsEOF(oldFile))
   {
   x = FileReadLine(oldFile);
   if(x eq lineToRemove)
      continue;
   WriteOutput("#x# <br>");
   FileWriteLine(newFile, x);
   }
   FileClose(oldFile);
   FileClose(newFile);
</cfscript>

That's it very simple code to remove the line from a file.

The test1.txt file just has this in it.

aaaaa
bbbbb
ccccc
ddddd
eeeee
fffff



  • CFneutral's Gravatar Personally the use on continue in this instance provides no benifit other then some additional confusion. I would suggest this syntax in replacement:

    if(x != lineToRemove){
    WriteOutput("#x# <br>");
    FileWriteLine(newFile, x);
    }

    I also prefer tradition operators ( ie != and == ) over eq and neq.
    # Posted By CFneutral | 9/6/09 7:00 AM
  • Andrew Scott's Gravatar @CFneutral - That is a matter of personal opinion only.
    # Posted By Andrew Scott | 9/6/09 9:53 PM
  • Dale Fraser's Gravatar Yeah the continue is bad practice.

    There is a good coding practice that says one entry and one exit point, you should try to do that as much as possible.

    The continue here is equivilant to a GOTO statement and adds no value.
    # Posted By Dale Fraser | 9/7/09 5:56 PM
  • Andrew Scott's Gravatar @Dale - You really can't put a continue and break into the same category as a goto statement, and as these both do add value for a means to break out of a loop. I do not see how this applies to the one entry one exit rule? There is also plenty of examples where a one entry one exit is just not practical as well.

    In the example above sure you could do it without the need to break out of the loop, but there are plenty of times when you do want to break out of a loop.

    Now as a break works very much like a continue, to some degree it would be interesting to note that in some langauges you need to use the break to exit a conditional case statement. And Adobe have made sure that you need this in the new cfscript case alternative. Without it you get the next case switch run when you don't want it too.
    # Posted By Andrew Scott | 9/8/09 2:30 AM