{"id":67163,"date":"2006-06-07T12:46:00","date_gmt":"2006-06-07T12:46:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/06\/07\/how-can-i-add-leading-zeroes-to-all-the-lines-in-a-text-file\/"},"modified":"2006-06-07T12:46:00","modified_gmt":"2006-06-07T12:46:00","slug":"how-can-i-add-leading-zeroes-to-all-the-lines-in-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-add-leading-zeroes-to-all-the-lines-in-a-text-file\/","title":{"rendered":"How Can I Add Leading Zeroes to All the Lines 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! I have a text file where each line is a set of characters like this: 56A63, 78A41, etc. I need to put leading zeroes in front of these strings in order to make them all nine characters long: 000056A63, 000078A41, etc. Oh: and my text file has 20,000 lines that need to be modified like this. How can I do all that using a script?<BR><BR>&#8212; JC<\/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, JC. You know, at first we were going to ask another one of the Scripting Guys to answer this question. For one thing, this Scripting Guy happens to be a world-class expert on scripting, and does a far better job of explaining complicated scripting techniques than the rest of us could even <I>dream<\/I> of doing. More important, she\u2019s playing in a Microsoft-sponsored softball league, and from what she\u2019s told us her batting average is <I>filled<\/I> with zeroes; she should have more than enough to share with you. <I>(Editor\u2019s Note: Keep in mind these biting comments came from the Scripting Guy who insists he\u2019s too good to play with the rest of us. Funny how none of us has ever actually seen him play though.)<\/I><\/P>\n<P>But then we thought, \u201cGosh, that would hardly be like <I>Hey, Scripting Guy!<\/I> to make fun of a co-worker.\u201d And so we decided to throw together this script instead:<\/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>Do Until objFile.AtEndOfStream\n    strText = objFile.ReadLine\n    intLength = Len(strText)\n    intZeroes = 9 &#8211; intLength\n    For i = 1 to intZeroes\n        strText = &#8220;0&#8221; &amp; strText\n    Next\n    strContents = strContents &amp; strText &amp; vbCrlf\nLoop<\/p>\n<p>objFile.Close<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)\nobjFile.WriteLine strContents<\/p>\n<p>objFile.Close\n<\/PRE>\n<P>Incidentally, we actually tested this on a text file with 20,000 lines in it. Not only did it work, but it worked pretty dang fast: in less than 30 seconds we were done. Which is just about the length of time it takes our fellow Scripting Guy to walk to the plate and then head back to the dugout, another at-bat over and done with.<\/P>\n<P>Not that we would mention anything like that, mind you.<\/P>\n<TABLE id=\"EJD\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P><B>Note<\/B>. At first we were concerned that our co-worker might work on her swing by taking a few cuts at <I>us<\/I>. But considering the way she hits a softball, well, we were willing to take that chance.<\/P>\n<P>And, yes, now that you mention it we <I>are<\/I> starting to get a little concerned for our safety.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>But what about the script? Well, we start out by defining a pair of constants, ForReading and ForWriting; we\u2019ll use these constants to indicate how we want to open the text file in question. As you know, we can\u2019t simultaneously read to <I>and<\/I> write from a text file; instead, we have to open the text file, read in the contents, modify those contents (by adding the leading zeroes), close the file, re-open the file, and <I>then<\/I> replace the existing lines with the modified lines. It\u2019s a tad bit cumbersome, but we don\u2019t have a lot of choice in the matter.<\/P>\n<P>After defining out constants we create an instance of the <B>Scripting.FileSystemObject<\/B>, the scripting object used for working with text files. We then call the <B>OpenTextFile<\/B> method, passing two parameters: the path to the file we want to open (C:\\Scripts\\Test.txt) and the constant ForReading. (Why ForReading? Because, as we noted a moment ago, the first step in this process is to read in the contents of the file.)<\/P>\n<P>With the file open we\u2019re ready to roll up our sleeves and get to work. What we\u2019re going to do next is read the file line-by-line, adding the leading zeroes as we go. To do that we set up a Do Until loop that runs from the beginning of the file to the end of the file. (How do we know that we\u2019ve reached the end of the file? We\u2019ve reached the end when the <B>AtEndOfStream<\/B> property is True.) Inside that loop we use this line of code to read the first line of the file and store the contents in a variable named strText:<\/P><PRE class=\"codeSample\">strText = objFile.ReadLine\n<\/PRE>\n<P>After we read in the line we\u2019re ready to add the leading zeroes. However, there\u2019s one complication here: as JC noted in her email, the number of characters in each line varies. That is, we might have <I>123<\/I> on one line, then have <I>12345<\/I> on another line. That means we can\u2019t simply add the same number of leading zeroes to each line and call it good. (Remember, the goal is to end up with a string nine characters long.)<\/P>\n<P>But that\u2019s a minor complication. To begin with, we use the <B>Len<\/B> function to determine the number of characters in strText. For example, suppose the first line in the text file is <I>1234<\/I>; in that case, Len will return a 4, because strText contains 4 characters. That\u2019s what this line of code does:<\/P><PRE class=\"codeSample\">intLength = Len(strText)\n<\/PRE>\n<P>Next we subtract the variable intLength (the length of the string) from 9. Why? Well, that tells us how many leading zeroes we need to add. With a 4-character string we subtract 4 from 9, leaving 5. That means we need to add 5 leading zeroes. Here\u2019s the line of code that carries out that calculation, with the required number of zeroes getting stored in a variable named intZeroes:<\/P><PRE class=\"codeSample\">intZeroes = 9 &#8211; intLength\n<\/PRE>\n<P>As far as adding the leading zeroes, we decided the easiest way to do that was to use a For Next loop that runs from 1 to the number of zeroes we need to add:<\/P><PRE class=\"codeSample\">For i = 1 to intZeroes\n    strText = &#8220;0&#8221; &amp; strText\nNext\n<\/PRE>\n<P>As you can see, each time through the loop we assign a new value to the variable strText: that new value is simply a 0 (as a character, not as a number) followed by the existing value of strText. The first time through the loop we\u2019ll have 0 followed by 1234, making strText equal to 01234. The second time through the loop we\u2019ll have 0 followed by 01234, yielding 001234. This continues until we have 9 characters in the string.<\/P>\n<P>The net effect: we\u2019ve now taken the first line of the text file and added the necessary leading zeroes. Ideally, at this point we\u2019d simply write the revised line back to the file. As we pointed out earlier, though, the FileSystemObject doesn\u2019t let us read and write to a file at the same time. Therefore we need to temporarily store all the revised lines in memory, something we do here:<\/P><PRE class=\"codeSample\">strContents = strContents &amp; strText &amp; vbCrlf\n<\/PRE>\n<P>All we\u2019re doing here is basically building our revised text file in memory. After the new file has been constructed we can then go ahead and write it to the actual file C:\\Scripts\\Test.txt.<\/P>\n<P>Next we loop around and repeat the process with the second line in the text file, eventually adding the modified second line (plus a carriage-return linefeed, represented by the VBScript constant <B>VbCrLf<\/B>) to the variable strContents. That means that, after we\u2019ve read through the entire file, strContents will contain 20,000 modified lines of text.<\/P>\n<P>All we need to do at that point is replace the existing contents of the text file with the 20,000 modified lines stored in strContents. To do that we close the file, then immediately re-open it, this time for writing:<\/P><PRE class=\"codeSample\">Set objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForWriting)\n<\/PRE>\n<P>We then call the <B>WriteLine<\/B> method to write the revised contents to the text file (overwriting the existing contents), a process that looks like this:<\/P><PRE class=\"codeSample\">objFile.WriteLine strContents\n<\/PRE>\n<P>And that\u2019s it. We close the text file, and we\u2019re free to move on to something else. Something like, say, batting practice.<\/P>\n<P>Well, for those of us who need it, that is \u2026.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have a text file where each line is a set of characters like this: 56A63, 78A41, etc. I need to put leading zeroes in front of these strings in order to make them all nine characters long: 000056A63, 000078A41, etc. Oh: and my text file has 20,000 lines that need to [&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-67163","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 text file where each line is a set of characters like this: 56A63, 78A41, etc. I need to put leading zeroes in front of these strings in order to make them all nine characters long: 000056A63, 000078A41, etc. Oh: and my text file has 20,000 lines that need to [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/67163","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=67163"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/67163\/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=67163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=67163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=67163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}