{"id":64763,"date":"2007-05-30T23:21:00","date_gmt":"2007-05-30T23:21:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/05\/30\/how-can-i-delete-the-first-line-and-the-last-line-in-a-text-file\/"},"modified":"2007-05-30T23:21:00","modified_gmt":"2007-05-30T23:21:00","slug":"how-can-i-delete-the-first-line-and-the-last-line-in-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-delete-the-first-line-and-the-last-line-in-a-text-file\/","title":{"rendered":"How Can I Delete the First Line and the Last Line in a Text File?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"> \n<P>Hey, Scripting Guy! How can I delete the first line and the last line in a text file?<BR><BR>&#8212; TF <\/P><IMG height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" height=\"288\" alt=\"Script Center\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" align=\"right\" border=\"0\"><\/A> \n<P>Hey, TF. We don\u2019t know if anyone has ever noticed, but <I>Hey, Scripting Guy!<\/I> tends to meander from time-to-time; there are those occasions when it seemingly takes <I>forever<\/I> for us to get around to answering the question of the day. Up until now we never really thought too much about that; so what if we don\u2019t get right to the point and take care of business? However, after what happened Sunday morning, we\u2019re beginning to re-think that approach.<\/P>\n<P>So what <I>did<\/I> happen Sunday morning? Well, Sunday morning the Scripting Guy who writes this column ran to the store to buy doughnuts. Now, the Scripting Guy who writes this column appreciates the importance of picking out the correct doughnuts; after all, that\u2019s likely the most important decision he\u2019ll make this week. (Maybe the <I>only<\/I> decision he\u2019ll make this week.) However, the man who reached the doughnut case seconds before the Scripting Guy who writes this column might have taken this careful consideration to the extreme.<\/P>\n<P>After getting his doughnut box and picking up one of the blue doughnut-grabbing tissues, the man stood in front of the case for what had to be several minutes, carefully pondering his choices. He grabbed a single glazed doughnut, placed it in the box, then resumed pondering. After several minutes he grabbed a maple bar, put <I>that<\/I> in his box, then pondered some more. The Scripting Guy who writes this column was too polite to do what he wanted to do, which was grab the man, shake him a couple times, and tell him, \u201cThese are doughnuts, for crying out loud! It doesn\u2019t matter; you can\u2019t go wrong with <I>any<\/I> kind of doughnut! Grab 12 somethings and get out of my way!\u201d<\/P>\n<P>Ay-yi-yi.<\/P>\n<P>This pattern continued for hours. Even worse, at one point the man changed his mind and put the glazed doughnut <I>back<\/I>! After taking several hours to pick out 5 doughnuts he was now back to having just 4! Awhile later he decided to rearrange the doughnuts in his box, moving the maple bar from the left side to the right and putting the two jelly doughnuts next to each other.<\/P>\n<P>That\u2019s right: ay-yi-yi.<\/P>\n<P>Under any other circumstances the Scripting Guy who writes this column would have gotten tired of waiting and just given up. But these are <I>doughnuts<\/I> we\u2019re talking about! So he waited. And waited.<\/P>\n<TABLE class=\"dataTable\" id=\"E5D\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P class=\"lastInCell\"><B>Note<\/B>. Of course, he could have done what these two women did, which was simply reach over and under the man and grab a few doughnuts of their own, at one point almost knocking the poor guy down in their quest to get a cinnamon twist. The Scripting Guy who writes this column decided he didn\u2019t want doughnuts <I>that<\/I> bad.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>At any rate, we realized that sometimes people appreciate it more if you just get to the point. And so we vowed that, from now on, <I>Hey, Scripting Guy!<\/I> would always get right to the point. No more meandering and messing around.<\/P>\n<P>Although, considering the fact that we\u2019re now 8 or 9 paragraphs into this column and all we\u2019ve talked about are doughnuts, well \u2026.<\/P>\n<P>But, hey, you know what they say: good things come to those who wait. Sometimes that means doughnuts, and sometimes that means scripts that can remove the first line and the last line from a text file:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objTextFile = objFSO.OpenTextFile(&#8220;c:\\Scripts\\Test.txt&#8221;, ForReading)<\/p>\n<p>strText = objTextFile.ReadAll\nobjTextFile.Close<\/p>\n<p>arrLines = Split(strText, vbCrLf)<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)<\/p>\n<p>For i = 1 to (Ubound(arrLines) &#8211; 1)\n    objFile.WriteLine arrLines(i)\nNext<\/p>\n<p>objFile.Close\n<\/PRE>\n<P>OK, let\u2019s see if we can figure out how this thing works. We start out by defining a pair of constants, ForReading and ForWriting; we\u2019ll need one of these constants each time we open the text file. And before you ask, yes, we\u2019re going to have to open the text file twice. Because we can\u2019t directly edit a text file using a script we need to open the file once in order to read from it. We\u2019ll read the file, store the contents in memory, then \u201cremove\u201d the first and last lines from this virtual copy of the file. We\u2019ll then open the file a second time (this time for writing) and replace the original contents with the virtual copy. <\/P>\n<P>With that in mind, our next step is to create an instance of the <B>Scripting.FileSystemObject<\/B> and then open the file C:\\Scripts\\Test.txt for reading:<\/P><PRE class=\"codeSample\">Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objTextFile = objFSO.OpenTextFile(&#8220;c:\\Scripts\\Test.txt&#8221;, ForReading)\n<\/PRE>\n<P>From there we use the <B>ReadAll<\/B> method to read the file and store the contents in a variable named strText. Once the file is read we then call the <B>Close<\/B> method and close the text file.<\/P>\n<P>Let\u2019s assume that this text file (and the value of the variable strText) looks like this:<\/P><PRE class=\"codeSample\">This is line 1.\nThis is line 2.\nThis is line 3.\nThis is line 4.\nThis is line 5.\n<\/PRE>\n<P>Our task now is to delete the first line and the last line. How are we going to do that? Well, for starters, we\u2019re going to use the <B>Split<\/B> function and turn our virtual text file into an array:<\/P><PRE class=\"codeSample\">arrLines = Split(strText, vbCrLf)\n<\/PRE>\n<P>As you can see, we\u2019re splitting the file on the carriage return-linefeed character (<B>vbCrLf<\/B>); that\u2019s going to result in an array where each item in the array corresponds to a line in the text file. In turn, that makes this the first item in the array:<\/P><PRE class=\"codeSample\">This is line 1.\n<\/PRE>\n<P>It also makes <I>this<\/I> the last item in the array:<\/P><PRE class=\"codeSample\">This is line 5.\n<\/PRE>\n<P>Believe it or not, we\u2019re now ready to write the revised contents back to the file. What\u2019s that? You say we didn\u2019t remove the first and last lines yet? That\u2019s true, and, to tell you the truth, we have no intention of removing the first and last lines. (That\u2019s why we said we would \u201cremove\u201d these lines.) But don\u2019t worry; the first and last lines will not appear in the text file. Guaranteed.<\/P>\n<P>Yes, it <I>is<\/I> kind of exciting, isn\u2019t it: how will the Scripting Guys escape from this trap they seem to have set for themselves? Well, to begin with, we re-open the file C:\\Scripts\\Test.txt. But this time, we open the file for writing:<\/P><PRE class=\"codeSample\">Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)\n<\/PRE>\n<P>So what are we going to write to the file? We\u2019re going to write the contents we read in from the text file \u2013 except, of course, for the first and last lines. That\u2019s the reason we have this block of code:<\/P><PRE class=\"codeSample\">For i = 1 to (Ubound(arrLines) &#8211; 1)\n    objFile.WriteLine arrLines(i)\nNext\n<\/PRE>\n<P>What we\u2019re doing here is setting up a For Next loop to loop through the items in the array arrLines. Wait, check that: to loop through <I>most<\/I> of the lines in the array arrLines. As you know, the first item in an array is always given the index number 0; that means that the second item in the array is given the index number 1. Well, notice where our For Next loop begins: it begins with item 1, the <I>second<\/I> item in the array. In other words, we\u2019re skipping item 1 (and thus line 1) altogether.<\/P>\n<P>You also know that the <B>Ubound<\/B> function identifies the last item in an array. OK, well, look at the endpoint of our For Next loop: <B>Ubound(arrLines) \u2013 1<\/B>. See? The last item in our loop is the upper bound of the array (Ubound) <I>minus 1<\/I>. Or, to put it another way, the next-to-last item in the array. That means we\u2019re skipping the very last item in the array as well. And that also means that we\u2019re skipping the very last line in the text file.<\/P>\n<P>So much for the For Next statement. Inside the loop we use the <B>WriteLine<\/B> method to write the value of each item in the array (except for the first item and the last item) back to the file C:\\Scripts\\Test.txt. What does that mean? That means that, when we\u2019re all done, Test.txt is going to look like this:<\/P><PRE class=\"codeSample\">This is line 2.\nThis is line 3.\nThis is line 4.\n<\/PRE>\n<P>It\u2019s our original file \u2026 minus the first and last lines. Pretty easy, wasn\u2019t it?<\/P>\n<P>As you know, we typically try to close each column with a punchline. Unfortunately, you\u2019ve probably already guessed the punchline to today\u2019s column. Sure enough, after selecting <I>his<\/I> doughnuts, the Scripting Guy who writes this column headed for the checkstand. Guess who was in line in front of him? And guess who couldn\u2019t find his club card? And guess who started to hand the clerk a $10 bill and then decided he\u2019d pay with exact change instead? And \u2013 well, you know the rest. Fortunately, the Scripting Guy who writes this column had picked up a dozen doughnuts; that ensured that he wouldn\u2019t starve to death while he waited in line.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I delete the first line and the last line in a text file?&#8212; TF Hey, TF. We don\u2019t know if anyone has ever noticed, but Hey, Scripting Guy! tends to meander from time-to-time; there are those occasions when it seemingly takes forever for us to get around to answering the [&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-64763","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 the first line and the last line in a text file?&#8212; TF Hey, TF. We don\u2019t know if anyone has ever noticed, but Hey, Scripting Guy! tends to meander from time-to-time; there are those occasions when it seemingly takes forever for us to get around to answering the [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64763","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=64763"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64763\/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=64763"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=64763"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=64763"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}