{"id":55403,"date":"2008-06-07T02:01:00","date_gmt":"2008-06-07T02:01:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/06\/07\/hey-scripting-guy-how-can-i-add-a-line-to-the-beginning-of-a-text-file-and-simultaneously-delete-the-last-line-of-that-file\/"},"modified":"2008-06-07T02:01:00","modified_gmt":"2008-06-07T02:01:00","slug":"hey-scripting-guy-how-can-i-add-a-line-to-the-beginning-of-a-text-file-and-simultaneously-delete-the-last-line-of-that-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-add-a-line-to-the-beginning-of-a-text-file-and-simultaneously-delete-the-last-line-of-that-file\/","title":{"rendered":"Hey, Scripting Guy! How Can I Add a Line to the Beginning of a Text File And Simultaneously Delete the Last Line of That File?"},"content":{"rendered":"<p><img decoding=\"async\" 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\" \/> <\/p>\n<p>Hey, Scripting Guy! I have a script that adds a line to a log file. Each time I add a new line to this file I would like to delete the last line in the file; that way I always have 20 lines in the file. Can you help me get this to work?<br \/>&#8212; HW<\/p>\n<p><img decoding=\"async\" border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\" \/><img decoding=\"async\" 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 decoding=\"async\" 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> <\/p>\n<p>Hey, HW. Well, today is Friday, June 6<sup>th<\/sup>, which means that the Scripting Guys have to get ready to head off for <a href=\"http:\/\/www.microsoft.com\/events\/teched2008\/itpro\/default.mspx\" target=\"_blank\"><b>TechEd Orlando<\/b><\/a> (where they\u2019ll be delivering two showings of the classic instructor-led lab <i>Windows PowerShell for VB<\/i><i>Scripter<\/i><i>s<\/i>). As we speak the Scripting Editor is working at home; that way she can both edit this column and pack for the trip. Meanwhile, the Scripting Guy who <i>writes<\/i> this column is sitting at work writing this column. Why isn\u2019t <i>he<\/i> home packing for the trip? That\u2019s easy: he doesn\u2019t need a lot of time to pack; instead, he has a system. Is he going to out of town for 4 days? No problem: right before he leaves he\u2019ll grab the first four shirts hanging in his closet; grab whatever happens to be lying on top of this sock and underwear drawer; toss the whole mess into a suitcase; and head for the airport. Mission accomplished!<\/p>\n<table id=\"ERD\" 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>. Actually, that\u2019s a little bit of an exaggeration. If he\u2019s going out of town for an extended period of time, he might also fold the shirts; that makes it easier to cram them all into the suitcase. But now that we think about it, that\u2019s about the only difference.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Anyway, the Scripting Guys are looking forward to returning to TechEd. After all, we have a lot of pleasant memories from TechEd 2007: riding Dudley Do-Right and Popeye and Bluto\u2019s Bilge Rat Barges at Universal Islands of Adventure; eating chocolate-filled pastries every morning for breakfast; dining on Cuban sandwiches and hot apple crisp at Universal City Walk \u2026.<\/p>\n<p>Oh. And that conference thing, too. <\/p>\n<p>Whatever it was.<\/p>\n<p>At any rate, if you\u2019re going to be at TechEd Orlando and you\u2019re looking for an introduction to Windows PowerShell, well, feel free to drop by one of our labs. We\u2019ll be doing one session at 10:00 AM Tuesday morning, then repeating that session at 1:00 PM Tuesday afternoon. We\u2019ll have some nice handouts for everyone who attends; in addition, we sent the Scripting Editor down into the basement and she emerged with the last two boxes of <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/funzone\/bobbles.mspx\"><b>Dr. Scripto bobblehead dolls<\/b><\/a>. We\u2019ll be giving away 12 bobbleheads in the morning session, and 12 more in the afternoon session.<\/p>\n<table id=\"EHE\" 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>. Can you attend both sessions, thus doubling your chances of winning a bobblehead? Sure; why not?<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>And what if you can\u2019t make it to TechEd Orlando; what then? Well, fortunately we have a consolation prize for you. It might not sound like much, but it\u2019s a script that can add a new line to a text file and, at the same time, remove the last line from that text file; in a recent poll many people said they would rather have a script like that than a trip to Florida.<\/p>\n<table id=\"ETE\" 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>. OK, it\u2019s <i>possible<\/i> that we might be mistaken about that. But while we\u2019re riding the water slides at Wet \u2018n Wild we\u2019ll be sure to ask people if they\u2019d rather be riding the water slides at Wet \u2018n Wild or reading about a script that can add a new line to a text file and, at the same time, remove the last line from that text file.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>At any rate, enjoy:<\/p>\n<pre class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(\"C:\\Scripts\\Test.txt\", ForReading)\n\nstrText = Now &amp; vbCrLf\n\nstrContents = objFile.ReadAll\narrContents = Split(strContents, vbCrlf)\n\nIf Ubound(arrContents) &lt; 20 Then\n    strText = strText &amp; strContents\nElse\n    For i = 0 to 18\n        strLine = arrContents(i)\n        strText = strText &amp; strLine &amp; vbCrLf\n    Next\nEnd If\n\nobjFile.Close\n\nSet objFile = objFSO.OpenTextFile(\"C:\\Scripts\\Test.txt\", ForWriting)\nobjFile.Write strText\nobjFile.Close\n<\/pre>\n<p>Before we launch into an explanation of the script and how it works, let\u2019s take a look at the text file in question:<\/p>\n<pre class=\"codeSample\">1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n<\/pre>\n<p>Pretty fancy, huh? Each time we run our script we want to insert a new line at the beginning of the file (for sample purposes we\u2019re just going to enter the date and time); at the same time we need to delete the last line of the file. (That way our file always has 20 lines in it.) In other words, after we run the script the first time the text file should look something like this:<\/p>\n<pre class=\"codeSample\">6\/5\/2008 10:43:08 AM\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n<\/pre>\n<p>Nice; <i>very<\/i> nice. But how do we make this happen?<\/p>\n<p>Well, to begin with, we define a pair of constants, ForReading and ForWriting; we\u2019ll need these two constants in order to open and work with the txt file C:\\Scripts\\Test.txt. After defining the constants we create an instance of the <b>Scripting.FileSystemObject<\/b>, then use the following line of code to open Test.txt for reading:<\/p>\n<pre class=\"codeSample\">Set objFile = objFSO.OpenTextFile(\"C:\\Scripts\\Test.txt\", ForReading)<\/pre>\n<p>You can already feel the excitement beginning to build, can\u2019t you?<\/p>\n<p>After the text file is open we pause for a moment to assign the current date and time (using the VBScript function <b>Now<\/b>) and a carriage return-linefeed character (<b>vbCrLf<\/b>) to a variable named strText:<\/p>\n<pre class=\"codeSample\">strText = Now &amp; vbCrLf<\/pre>\n<p>As you might have guessed, this is the new value we\u2019re going to add to the text file. (Of course, you really didn\u2019t need to guess that; we mentioned earlier that we were going to add the current date and time to the file.) We then use the <b>ReadAll<\/b> method to read in the entire contents of the file and store that information in a variable named strContents:<\/p>\n<pre class=\"codeSample\">strContents = objFile.ReadAll<\/pre>\n<p>Of course, we don\u2019t really want to work with the text file contents as a whole; what we really want to work with are the individual lines in the file. (That way we can more easily insert a line at the beginning and chop off a line at the end.) Therefore, the next thing we do is use the <b>Split<\/b> function to split the contents of the file (the value of strContents) into an array:<\/p>\n<pre class=\"codeSample\">arrContents = Split(strContents, vbCrlf)<\/pre>\n<p>By splitting on the carriage return-linefeed that turns arrContents into an array in which item represents an individual line in the text file.<\/p>\n<p>And yes, that <i>is<\/i> kind of cool, isn\u2019t it? Let\u2019s just hope that the Nobel Prize Committee is paying attention.<\/p>\n<p>You know what: we lied. Well, OK, it wasn\u2019t really a <i>lie<\/i>, but we didn\u2019t give you the entire picture. Just a second ago we said \u201c\u2026we don\u2019t really want to work with the text file contents as a whole; what we really want to work with are the individual lines in the file.\u201d That\u2019s true, <i>unless<\/i> the text file has less than 20 lines in it. After all, suppose the text file has 1 line in it. If we add a new line at the beginning and then chop off the last line, well, how many lines will the text file have in it? That\u2019s right: just 1. Not exactly what we want.<\/p>\n<table id=\"EWG\" 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>. By the way, good answer to the last question. Now try this one: Two trains leave Los Angeles 3 hours apart, headed for St. Louis. Train 1, which left at noon, travels at 50 miles an hour. Train 2, which left at 3:00 PM, travels at 65 miles an hour. Now, why would anyone want to take the train from Los Angeles to St. Louis?<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Because of that, the next thing we do is check to see if the last item in the array arrContents (<b>UBound<\/b>) has an index number less than 20. If it does, then there\u2019s no need to delete the last line in the text file; after all, we\u2019re nowhere near the 20-line limit. That makes life easier; all we have to do is add the new value (strText) to the beginning of the file contents, like so:<\/p>\n<pre class=\"codeSample\">strText = strText &amp; strContents<\/pre>\n<p>We should probably mention that if your text file has <i>no<\/i> lines in it then you\u2019re going to run into trouble here; that\u2019s because attempting to read an empty text file results in an error. If there\u2019s a chance you might have an empty file you might want to verify the size of the file before trying to read it; fortunately <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/scripts\/misc\/text\/mstxvb11.mspx\" target=\"_blank\"><b>we have a script<\/b><\/a> that shows you how to do just that. If the file <i>is<\/i> empty then you can simply write the new value to the file, without having to read from it.<\/p>\n<p>But what if our text file already <i>has<\/i> 20 lines in it? (And what if it has more? No problem; by the time this script finishes running we\u2019ll have trimmed it back down to the 20-line limit.) Well, if our text file already has 20 (or more) lines then we execute this block of code:<\/p>\n<pre class=\"codeSample\">For i = 0 to 18\n    strLine = arrContents(i)\n    strText = strText &amp; strLine &amp; vbCrLf\nNext\n<\/pre>\n<p>What&nbsp;are we doing here? To begin with, we\u2019ve set up a For Next loop that runs from 0 to 18. Why? Well, we want to snag the first 19 lines in the text file; we don\u2019t want anything to do with line 20 or any lines beyond that. Because the first item in an array has the index number 0, our loop needs to run from 0 to 18 rather than 1 to 19.<\/p>\n<p>But you already knew that, didn\u2019t you?<\/p>\n<p>Inside the loop we use this line of code to grab the array item corresponding to the value of our counter variable i:<\/p>\n<pre class=\"codeSample\">strLine = arrContents(i)<\/pre>\n<p>In other words, the first time through the loop i will be equal to 0; thus we\u2019ll be grabbing the value of array item 0. And what <i>is<\/i> the value of array item 0? That\u2019s right: it\u2019s the first line in the text file.<\/p>\n<p>Man, are you guys on a roll or <i>what<\/i> when it comes to answering questions today?<\/p>\n<p>In line 2 we then tack this value (plus a carriage return-linefeed) onto the end of the variable strText. That\u2019s going to make the first line in strText equal to the current date and time, and the second line equal to the first line in the text file. (See how that works? We\u2019re essentially inserting a new line at the beginning of the file.) By the time we reach the end of the loop the 20<sup>th<\/sup> and last line in strText will be the 19<sup>th<\/sup> line in the text file.<\/p>\n<table id=\"ESAAC\" 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 stop and visualize what we\u2019re doing it should all be clear. Just imagine a space that can only hold 20 lines of text. When we insert a new line at the beginning that pushes all the other lines down one spot, and causes the 20<sup>th<\/sup> and last line to fall out of the space altogether.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>At this point we\u2019re almost done; all we have to do is close the file Test.txt, then immediately reopen it, this time for writing:<\/p>\n<pre class=\"codeSample\">Set objFile = objFSO.OpenTextFile(\"C:\\Scripts\\Test.txt\", ForWriting)\nobjFile.Write strText\nobjFile.Close\n<\/pre>\n<p>Once the file has been reopened we use the <b>Write<\/b> method to replace the existing contents with the value of strText. We close the file one last time, and then call it a day, another job well done:<\/p>\n<pre class=\"codeSample\">6\/5\/2008 10:43:08 AM\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n<\/pre>\n<p>That&nbsp;should do it, HW; at some point even the Scripting Guy who writes this column needs to get ready to head down to Florida. Let\u2019s see, swimming suit; sunglasses; margarita glass; beach towel \u2026.<\/p>\n<p>Oh, yeah: and slides for the instructor-led lab. We were just about to mention those \u2026. See you on Monday &#8230; from Florida!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have a script that adds a line to a log file. Each time I add a new line to this file I would like to delete the last line in the file; that way I always have 20 lines in the file. Can you help me get this to work?&#8212; HW [&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-55403","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! I have a script that adds a line to a log file. Each time I add a new line to this file I would like to delete the last line in the file; that way I always have 20 lines in the file. Can you help me get this to work?&#8212; HW [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55403","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=55403"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55403\/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=55403"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=55403"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=55403"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}