{"id":66503,"date":"2006-09-11T15:11:00","date_gmt":"2006-09-11T15:11:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/09\/11\/how-can-i-delete-just-the-last-line-of-a-text-file\/"},"modified":"2006-09-11T15:11:00","modified_gmt":"2006-09-11T15:11:00","slug":"how-can-i-delete-just-the-last-line-of-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-delete-just-the-last-line-of-a-text-file\/","title":{"rendered":"How Can I Delete Just the Last Line of a Text File?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> \n<P>Hey, Scripting Guy! How can I delete just the last line of a text file?<BR><BR>&#8212; AD<\/P><IMG border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/A> \n<P>Hey, AD. You know, it\u2019s been a long, hard day here at Microsoft, one of those days when everyone and everything seems to be against you. Many people, when faced with a day like today, turn to the so-called comfort foods: meatloaf, beef stew, mashed potatoes and gravy, any food that\u2019s familiar and reliable. When you\u2019re a Scripting Guy faced with a day like today, you turn to the so-called comfort <I>scripts<\/I>: reading from and writing to text files. Familiar and reliable.<\/P>\n<TABLE id=\"E6C\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. Admittedly, we Scripting Guys would prefer to turn to comfort foods ourselves. However, we\u2019re stuck with comfort scripts, at least until they start putting mashed potatoes and gravy into the vending machines around here.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>It\u2019s nowhere near as good as a meatloaf sandwich, but here\u2019s a script that deletes just the last line of a text file: <\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>Set objFSo = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;c:\\scripts\\test.txt&#8221;, ForReading)<\/p>\n<p>strContents = objFile.ReadAll\nobjFile.Close<\/p>\n<p>arrLines = Split(strContents, vbCrLf)<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;c:\\scripts\\test.txt&#8221;, ForWriting)<\/p>\n<p>For i = 0 to UBound(arrLines) &#8211; 1\n    objFile.WriteLine arrLines(i)\nNext<\/p>\n<p>objFile.Close\n<\/PRE>\n<P>Actually, no, we hadn\u2019t planned on explaining how the script works; when you order a meatloaf sandwich no one ever explains how <I>that\u2019s<\/I> made, do they? <\/P>\n<P>Oh, fine; we\u2019ll see what we can do. We start out by defining a pair of constants, ForReading and ForWriting; we\u2019ll use these constants to specify read-only or write-only mode when opening the text file. As usual, we need to open this file twice. In just a second we\u2019re going to open the file for reading, and read in the existing contents. We\u2019ll close the file, modify the contents in memory, then reopen the file and save the modified contents (that is, the old contents minus the very last line). It\u2019s a bit of a hassle, but we have little choice here: the FileSystemObject won\u2019t let us open a file for both reading and writing. Instead, at any given time we\u2019re limited to doing one of those operations or the other.<\/P>\n<P>And, yes, that is a bit like eating the mashed potatoes, and only then being able to eat the gravy, isn\u2019t it?<\/P>\n<P>After defining the two constants we create an instance of the <B>Scripting.FileSystemObject<\/B> and use the <B>OpenTextFile<\/B> method to open the file C:\\Scripts\\Testtxt. With the file open for reading we then use this line of code to read the entire text file and store the contents in a variable named strContents:<\/P><PRE class=\"codeSample\">strContents = objFile.ReadAll\n<\/PRE>\n<P>With the entire file stashed safely away in memory we then call the Close method to (temporarily) close the file.<\/P>\n<P>Now what? As it turns out, our next step is to use the <B>Split<\/B> function to split the contents of the file into an array name arrLines, with each item in the array representing a line in the text file. We do that by splitting on the carriage return-linefeed character (or, as VBScript knows this character, <B>vbCrLf<\/B>):<\/P><PRE class=\"codeSample\">arrLines = Split(strContents, vbCrLf)\n<\/PRE>\n<P>Why do we do that? Well, the FileSystemObject doesn\u2019t really know much about text files; for example, it doesn\u2019t know which line is the last line in a given file. In that respect, arrays are a little smarter than the FileSystemObject. After all, any array can tell what its last item is: you can determine the last item in an array simply by calling the <B>Ubound<\/B> function, which returns the index number (subscript) of that item. For example, if the Ubound function returns a 13, then the last item in the array must have an index number of 13; in turn, that would mean thet we\u2019re dealing with arrLines(13).<\/P>\n<P>Hold on; we\u2019re getting to that. So why is it useful to know that which item is the last item in the array? Well, we don\u2019t want the last item to be included in our revised text file. If we know that the last item is item 13, then we know that our revised text file should only include items 0 through 12 (remember, the first item in an array is always item 0). We want to grab items 0 through 12 and then stop; that effectively deletes the last line in the text file.<\/P>\n<P>Good idea: maybe we should just show you what we mean. After creating the array we reopen the text file, this time for writing; as you know, information we write to the file will completely replace the existing contents of the file. We then set up a For Next loop that runs from 0 to the Ubound value of the array minus 1:<\/P><PRE class=\"codeSample\">For i = 0 to UBound(arrLines) &#8211; 1\n<\/PRE>\n<P>Boy, you have a lot of questions today, don\u2019t you? Why Ubound minus 1? Well, the Ubound function identifies the last item in the array. As we know, we don\u2019t want the last item; however, we do want all the items up to \u2013 but not including \u2013 the last item. If the last item in the array is item 13, taking the Ubound value (13) and subtracting 1 leaves us with 12, which turns out to be the very value we need in our For Next loop. (To get items 0 through 12 our loop needs to run from 0 to, well, 12.) That\u2019s why we use Ubound minus 1.<\/P>\n<P>Inside our loop, and on the first go-round, we use the WriteLine method to write the value of array item 0 (the first item in the array, represented by the counter variable i) to the text file:<\/P><PRE class=\"codeSample\">objFile.WriteLine arrLines(i)\n<\/PRE>\n<P>We then loop around and repeat the process with the counter variable i equal to 1, meaning that we\u2019ll write the value of array item 1 to the text file. This continues until we write the value of item 12 (the next-to-last item in the array) and then exit the loop. At that point we close the file and call it a day, without ever writing the last item in the array to the text file. We took a somewhat roundabout path here, but the net effect is that we\u2019ve deleted the last line in the text file (simply by rewriting all the lines except the last line).<\/P>\n<P>So will this really work? Of course it will. Suppose our text file looks like this, with the letter E being the actual last line of the file (that is, there\u2019s no blank line following it):<\/P><PRE class=\"codeSample\">A\nB\nC\nD\nE\n<\/PRE>\n<P>What do you get back when you run the script? This:<\/P><PRE class=\"codeSample\">A\nB\nC\nD\n<\/PRE>\n<TABLE id=\"EWE\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. So what if your text file <I>does<\/I> have a blank line at the end? One thing you could do is check for that possibility \u2013 and remove the blank line \u2013 before you convert the text file to an array. Fortunately, we have a <A href=\"http:\/\/null\/technet\/scriptcenter\/resources\/qanda\/may05\/hey0520.mspx\"><B>Hey, Scripting Guy! column<\/B><\/A> that tells you how to do that very thing.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>And that\u2019s how the script works. As for the meatloaf sandwich, take two pieces of bread, put a little mustard on both pieces, and then slap a hunk of meatloaf in the middle. Feel free to use this recipe any time. Just make sure you credit the Scripting Guys.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I delete just the last line of a text file?&#8212; AD Hey, AD. You know, it\u2019s been a long, hard day here at Microsoft, one of those days when everyone and everything seems to be against you. Many people, when faced with a day like today, turn to the so-called [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[3,4,14,5],"class_list":["post-66503","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-scripting-guy","tag-scripting-techniques","tag-text-files","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! How can I delete just the last line of a text file?&#8212; AD Hey, AD. You know, it\u2019s been a long, hard day here at Microsoft, one of those days when everyone and everything seems to be against you. Many people, when faced with a day like today, turn to the so-called [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66503","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=66503"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66503\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=66503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=66503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=66503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}