{"id":69063,"date":"2005-08-30T13:32:00","date_gmt":"2005-08-30T13:32:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2005\/08\/30\/how-can-i-increment-the-last-line-in-a-text-file\/"},"modified":"2005-08-30T13:32:00","modified_gmt":"2005-08-30T13:32:00","slug":"how-can-i-increment-the-last-line-in-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-increment-the-last-line-in-a-text-file\/","title":{"rendered":"How Can I Increment the Last Line in 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 increment the last line in a text file; that is, if the last line is 1, indicating we\u2019ve done one backup, I need to increment it to 2, indicating that we\u2019ve now done a second backup.<BR><BR>&#8212; TH<\/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, TH. If you\u2019ve ever been to a carnival then you\u2019ve no doubt been tempted by some of the sideshow games. Throw a baseball and knock down a few milk cans? Toss a dime into a glass bowl? Break a balloon with a <I>dart<\/I>, for Pete\u2019s sake?!? How hard could <I>that<\/I> be?<\/P>\n<P>Well, if you\u2019ve <I>never<\/I> been to a carnival here\u2019s a word to the wise: those things are actually way harder than they look. Just because something sounds like it should be easy doesn\u2019t mean it really <I>is<\/I> easy. You\u2019d be surprised how hard &#8211; and how expensive &#8211; it can be to toss a rubber ring onto a glass bottle. <\/P>\n<TABLE id=\"EHD\" 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>. If you\u2019re bound and determined to try these games anyway, you might find some helpful hints <A href=\"http:\/\/vt.essortment.com\/beatcarnivalga_rayx.htm\" target=\"_blank\"><B>here<\/B><\/A>. All part of the Scripting Guys customer service!<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>We mention all this because your question would make the perfect carnival game. After all, it sounds easy enough: you just open the text file, go to the last line, and change it. How hard could <I>that<\/I> be? Well, due to the limitations of the FileSystemObject (the scripting technology used to read and write text files) it\u2019s actually much harder than it probably should be. That doesn\u2019t mean this can\u2019t be done; it just means that the script will &#8211; at first glance &#8211; look a little more complicated than you might expect. Forewarned is forearmed, you know.<\/P>\n<P>In other words, the script will look like this:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>Dim arrFileLines()\ni = 0<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForReading)<\/p>\n<p>Do Until objFile.AtEndOfStream\n     Redim Preserve arrFileLines(i)\n     arrFileLines(i) = objFile.ReadLine\n     i = i + 1\nLoop<\/p>\n<p>objFile.Close<\/p>\n<p>intLastLine = Ubound(arrFileLines)\nintNumber = arrFileLines(intlastLine)\nintNumber = intNumber + 1<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;c:\\scripts\\test.txt&#8221;, ForWriting)<\/p>\n<p>For i = 0 to Ubound(arrFileLines) &#8211; 1\n    objFile.WriteLine arrFileLines(i)\nNext<\/p>\n<p>objFile.WriteLine intNumber<\/p>\n<p>objFile.Close\n<\/PRE>\n<P>Before we explain how the script works, we\u2019re assuming you have a text file that looks something like this:<\/P><PRE class=\"codeSample\">A\nB\nC\nD\nE\n31\n<\/PRE>\n<P>Granted, it probably doesn\u2019t look <I>exactly<\/I> like that, but the point is that you have a few lines of text (and, most likely, you aren\u2019t sure how <I>many<\/I> lines of text) followed by the backup number. The next time you run the script you want the text file to look like this:<\/P><PRE class=\"codeSample\">A\nB\nC\nD\nE\n32\n<\/PRE>\n<P>In other words, everything remains the same except for the backup number, which gets incremented from 31 to 32. Given the limitations of the FileSystemObject (having to open a file for reading <I>or<\/I> for writing, but not for both; being unable to go directly to the last line in a file; etc.) how do we go about doing that?<\/P>\n<P>Well, we start by creating a pair of constants: ForReading and ForWriting. We\u2019ll use these later in the script to open our text file in the appropriate mode. (As we noted a moment ago, you must open a text file for reading <I>or<\/I> for writing; you can\u2019t perform both operations simultaneously.) We then define an array variable named arrFileLines; we\u2019ll use this variable to store the existing contents of the text file. Why? We\u2019ll explain that momentarily.<\/P>\n<P>After opening the file C:\\Scripts\\Test.txt, we then use this block of code to read the file line-by-line and store the individual lines as items in the array arrFileLines:<\/P><PRE class=\"codeSample\">Do Until objFile.AtEndOfStream\n     Redim Preserve arrFileLines(i)\n     arrFileLines(i) = objFile.ReadLine\n     i = i + 1\nLoop\n<\/PRE>\n<P>We do this for two reasons. First, we need to be able to access &#8211; and change &#8211; the very last line in the file. The FileSystemObject doesn\u2019t have a method that enables us to jump directly to the last line in the file; by storing the individual lines in an array, however, we cause VBScript to access the last item in the array (which will also be the last line in the file.) In addition, the FileSystemObject doesn\u2019t allow us to change a single line in a text file; instead, we\u2019re going to have to replace the existing contents of Test.txt with a brand-new file. That new file will include the first <I>x<\/I> lines (unchanged) in Test.txt plus a new, modified last line. By storing the existing contents in an array it will be easy for us to recall all the lines in the file except for the very last line. <\/P>\n<P>That might not make a whole lot of sense right now, but it should become a bit clearer when we actually update the file. And, yes, there are a couple other ways we could have done this, but this way (believe it or not) seemed the simplest and most straightforward.<\/P>\n<P>After reading the file we immediately close it, then use these three lines of code to figure out the current backup number and increment it by 1:<\/P><PRE class=\"codeSample\">intLastLine = Ubound(arrFileLines)\nintNumber = arrFileLines(intlastLine)\nintNumber = intNumber + 1\n<\/PRE>\n<P>What we\u2019re doing here is using the <B>Ubound<\/B> function to determine the index number of the last item in the array. (Items in an array are assigned index numbers: the first item in the array is item 0, the second item in the array is item 1, and so on.) Once we know the index number for the last item (in this case it will be 5, because we have 6 items &#8211; or lines &#8211; in our array) we can then assign the value of the last item to the variable intNumber. That takes place here:<\/P><PRE class=\"codeSample\">intNumber = arrFileLines(intlastLine)\n<\/PRE>\n<P>The value of the last item in the array is 31; that\u2019s because the last line in our text file is 31. We then use this line of code to add 1 to the existing value (which, in this example, will add 1 to 31):<\/P><PRE class=\"codeSample\">intNumber = intNumber + 1\n<\/PRE>\n<P>Make sense? All we\u2019ve done so far is just up the backup number from 31 to 32. But, really, that\u2019s all we <I>need<\/I> to do: we\u2019re now ready to re-open the file C:\\Scripts\\Test.txt and replace the current contents with the revised contents. To do that we use this block of code to write all the existing lines <I>except the last line<\/I> to the file:<\/P><PRE class=\"codeSample\">For i = 0 to Ubound(arrFileLines) &#8211; 1\n    objFile.WriteLine arrFileLines(i)\nNext\n<\/PRE>\n<P>In other words, we\u2019re going to write the following lines to the text file:<\/P><PRE class=\"codeSample\">A\nB\nC\nD\nE\n<\/PRE>\n<P>Why didn\u2019t we write the last line? Well, remember, in our array the last line is this:<\/P><PRE class=\"codeSample\">31\n<\/PRE>\n<P>We want our new, incremented value (32) to be the <I>new<\/I> last line in the file. Therefore, we use this line of code to tack the value 32 (representing the current backup number) to the end of the text file:<\/P><PRE class=\"codeSample\">objFile.WriteLine intNumber\n<\/PRE>\n<P>We then close the file and we\u2019re done. Our text file should now look like this, which just happens to be the way we <I>wanted<\/I> it to look:<\/P><PRE class=\"codeSample\">A\nB\nC\nD\nE\n32\n<\/PRE>\n<P>And, yes, it\u2019s a bit unfair that you can get a stuffed bear for tossing a dime into a bowl, yet you probably <I>won\u2019t<\/I> get a stuffed bear for incrementing the last line in a text file. Life can be very cruel sometimes, can\u2019t it?<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I increment the last line in a text file; that is, if the last line is 1, indicating we\u2019ve done one backup, I need to increment it to 2, indicating that we\u2019ve now done a second backup.&#8212; TH Hey, TH. If you\u2019ve ever been to a carnival then you\u2019ve no [&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-69063","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 increment the last line in a text file; that is, if the last line is 1, indicating we\u2019ve done one backup, I need to increment it to 2, indicating that we\u2019ve now done a second backup.&#8212; TH Hey, TH. If you\u2019ve ever been to a carnival then you\u2019ve no [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/69063","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=69063"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/69063\/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=69063"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=69063"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=69063"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}