{"id":65803,"date":"2007-01-04T17:27:00","date_gmt":"2007-01-04T17:27:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/01\/04\/how-can-i-number-the-lines-in-a-text-file\/"},"modified":"2007-01-04T17:27:00","modified_gmt":"2007-01-04T17:27:00","slug":"how-can-i-number-the-lines-in-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-number-the-lines-in-a-text-file\/","title":{"rendered":"How Can I Number the Lines 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 number the lines in a text file?<BR><BR>&#8212; AS<\/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, AS. You know, after being on vacation for three weeks the Scripting Guy who writes this column has a lot of catching up to do. In turn, that means that <I>you<\/I> have a lot of catching up to do. For example, did you know that the Seattle area experienced a huge power outage shortly before Christmas? Well, it\u2019s true; in fact, the Scripting Guy who writes this column went six days before power was restored to his house. Did desperation set in for the Scripting Family? Let\u2019s put it this way: they were just about to draw lots to determine which family member would be killed and eaten when the power miraculously came back on. <\/P>\n<P>OK, to be honest it wasn\u2019t quite <I>that<\/I> bad. For example, the Scripting family room stayed at a (relatively) balmy 50 degrees Fahrenheit, which meant that at least one portion of the house was (relatively) inhabitable. What about the <I>rest<\/I> of the house? Well, after a couple of days the Scripting Guy who writes this column noticed that the ice in the freezer was starting to melt. Therefore, he dumped all the ice into the sink. Two days later, the ice was still there; it had barely melted at all. In other words, it was warmer in the freezer than it was in the rest of the house.<\/P>\n<P>Which is usually not a very good sign.<\/P>\n<P>Of course, one <I>advantage<\/I> to not having any electricity was the fact that it gave the Scripting Guy who writes this column lots of time to just sit and think. And what did he think about? Why, how to write a script that would number all the lines in a text file, of course.<\/P>\n<P>OK, that\u2019s not really true, either; instead, he spent most of his time thinking about the best way, if worse came to worse, to barbecue the Scripting Son. <I>(Editor\u2019s Note: Is anyone else getting a little grossed out at this point?)<\/I> The Scripting Guy who writes this column just <I>said<\/I> that he thought about writing a script that would number all the lines in a text file because it made a nice lead-in to this, a script which actually <I>does<\/I> number all the lines in a text file:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>i = 1<\/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    strLine = objFile.ReadLine\n    strContents = strContents &amp; i &amp; &#8221;   &#8221; &amp; strLine &amp; vbCrLf\n    i = i + 1\nLoop<\/p>\n<p>objFile.Close<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)\nobjFile.Write strContents\nobjFile.Close\n<\/PRE>\n<P>Let\u2019s see if we can figure out how this baby works. We begin by defining a pair of constants \u2013 ForReading and ForWriting \u2013 that we\u2019ll use when working with the text file. We then set the value of a counter variable named <I>i<\/I> to 1; we\u2019ll use this variable to keep track of line numbers.<\/P>\n<P>Got all that? Good. Now we\u2019re ready to start. To begin with, we use these two lines of code to create an instance of the <B>Scripting.FileSystemObject<\/B> and then open the file C:\\Scripts\\Test.txt:<\/P><PRE class=\"codeSample\">Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForReading)\n<\/PRE>\n<P>You might have noticed that we opened the file for reading (hence the use of the constant ForReading). As most of you know by now, that\u2019s due to a quirk in the FileSystemObject: you can open a file for reading or you can open a file for writing, but you can\u2019t do both operations (reading and writing) at the same time. Because of that we need to read the file into memory, add the line numbers to this \u201cvirtual\u201d copy of the file, then reopen the file for writing and replace the existing lines with the newly-numbered lines. <\/P>\n<P>To that end we first set up a Do Until loop that runs until we reach the end of the file (that is, until the file\u2019s <B>AtEndOfStream<\/B> property is True). Inside the loop we use the <B>ReadLine<\/B> method to read the first line of the file, storing that value in a variable named strLine. That brings us to this line of code:<\/P><PRE class=\"codeSample\">strContents = strContents &amp; i &amp; &#8221;   &#8221; &amp; strLine &amp; vbCrLf\n<\/PRE>\n<P>This is the code we use to construct a new file in memory, a file in which each line is numbered. As you can see, what we\u2019re doing here is assigning a value to a variable named strContents. What value are we assigning to the variable? We\u2019re assigning it the following:<\/P>\n<TABLE class=\"\" cellSpacing=\"0\" cellPadding=\"0\" border=\"0\">\n<TBODY>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The current value of strContents (which, the first time through the loop, is nothing).<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The value of the counter variable i (which, the first through the loop, is 1).<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>Three blank spaces.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The value of the variable strLine (which, the first time through the loop, is equal to the first line in the text file).<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>A carriage return-linefeed (represented by the VBScript constant vbCrLf).<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>For example, suppose our text file looks like this:<\/P><PRE class=\"codeSample\">This is line 1.\nThis is line 2.\nThis is line 3.\nThis is line 4.\n<\/PRE>\n<P>When we run through the loop the first time, our \u201cequation\u201d will look like this:<\/P><PRE class=\"codeSample\">[nothing]\n+                            1\n+         [three blank spaces]\n+ [a carriage return-linefeed]\n<\/PRE>\n<P>In turn, that means strContents will be equal to this:<\/P><PRE class=\"codeSample\">1   This line 1.\n<\/PRE>\n<P>We then increment the value of <I>i<\/I> by 1, loop around and repeat the process with the second line of the text file. At the end of this second loop strContents will be equal to this:<\/P><PRE class=\"codeSample\">1   This line 1.\n2   This line 2.\n<\/PRE>\n<P>And so on. When we\u2019re all done strContents will be equal to this:<\/P><PRE class=\"codeSample\">1   This line 1.\n2   This line 2.\n3   This line 3.\n4   This line 4.\n<\/PRE>\n<P>Which, in fortuitous fashion, just happens to be what we want our text file to look like.<\/P>\n<P>In a perfect world we\u2019d now simply replace the old contents of Test.txt with these new and improved contents. As the Scripting Guy who writes this column can attest, however, this isn\u2019t always a perfect world. That\u2019s as true of the FileSystemObject as it is the power grid. We <I>want<\/I> to simply replace the contents of Test.txt just like we <I>want<\/I> to be able to go to bed at night without having to wear long underwear, sweatpants, a sweatshirt, and a knitted ski cap. But, as the Rolling Stones warned us years ago, you can\u2019t always get what you want.<\/P>\n<P>Therefore, we need to take a somewhat more circuitous path. (Hey, how about that? We used both <I>fortuitous<\/I> and <I>circuitous<\/I> in the same column. We\u2019ll try to fit in <I>gratuitous<\/I> if at all possible.) For starters, we use the <B>Close<\/B> method to close our text file:<\/P><PRE class=\"codeSample\">objFile.Close\n<\/PRE>\n<P>We then turn right around and reopen the file, this time for writing:<\/P><PRE class=\"codeSample\">Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)\n<\/PRE>\n<P>As soon as the file is reopened we can then call the <B>Write<\/B> method and write the value of strContents to Test.txt. After we call the Close method to close the file Test.txt will look like this:<\/P><PRE class=\"codeSample\">1   This line 1.\n2   This line 2.\n3   This line 3.\n4   This line 4.\n<\/PRE>\n<P>And there you have it. <\/P>\n<P>And, to be honest, there truly <I>was<\/I> one nice thing about the blackout: it gave the Scripting Guy who writes this column an opportunity to prove that he was every bit as rugged and resourceful as people who lived in the days before electricity and modern conveniences. Of course, that\u2019s assuming that those people just hopped in the car and drove to a nearby restaurant any time they got hungry. (Most areas around Seattle had power restored within two days.) And that they were able to while away those long, cold winter nights by attending a college basketball game; the University of Washington lost power only briefly, if at all. And that, instead of huddling together during the day in order to keep warm, they went Christmas shopping at the mall.<\/P>\n<P>But that seems reasonable enough to assume.<\/P><BR>\n<DIV>\n<TABLE class=\"\" cellSpacing=\"0\" cellPadding=\"0\" width=\"100%\" border=\"0\">\n<TBODY>\n<TR>\n<TD class=\"\"><A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/jan07\/hey0104.mspx#top\"><IMG height=\"9\" alt=\"Top of page\" src=\"http:\/\/www.microsoft.com\/technet\/mnplibrary\/templates\/MNP2.Common\/images\/arrow_px_up.gif\" width=\"7\" border=\"0\"><\/A><A class=\"topOfPage\" href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/jan07\/hey0104.mspx#top\">Top of page<\/A><\/TD><\/TR><\/TBODY><\/TABLE><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I number the lines in a text file?&#8212; AS Hey, AS. You know, after being on vacation for three weeks the Scripting Guy who writes this column has a lot of catching up to do. In turn, that means that you have a lot of catching up to do. For [&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-65803","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 number the lines in a text file?&#8212; AS Hey, AS. You know, after being on vacation for three weeks the Scripting Guy who writes this column has a lot of catching up to do. In turn, that means that you have a lot of catching up to do. For [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65803","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=65803"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65803\/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=65803"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=65803"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=65803"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}