{"id":66043,"date":"2006-11-14T16:26:00","date_gmt":"2006-11-14T16:26:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/11\/14\/how-can-i-extract-information-located-between-two-known-values-in-a-text-file\/"},"modified":"2006-11-14T16:26:00","modified_gmt":"2006-11-14T16:26:00","slug":"how-can-i-extract-information-located-between-two-known-values-in-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-extract-information-located-between-two-known-values-in-a-text-file\/","title":{"rendered":"How Can I Extract Information Located Between Two Known Values in a Text 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! In a text file, how can I extract the information that appears between the string HOSTNAME= and a blank space?<\/p>\n<p>&#8212; B<\/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, B. You\u2019ll have to pardon us if we seem a little sluggish today; we\u2019re still recovering from all the fun and excitement of Windows PowerShell Week. What if you missed out on Windows PowerShell Week? Well, then you really blew it, didn\u2019t you? Now you\u2019ll never get to learn about Windows PowerShell, you\u2019ll lose your job, your dog will bite you, and your spouse will pack up and leave.<\/p>\n<p>OK, so maybe there is at least <i>one<\/i> advantage to having missed Windows PowerShell Week, if you know what we mean.<\/p>\n<p>Just a second, B .\u2026 <\/p>\n<p>Sorry; apparently the Scripting Editor has discovered a typo in the first paragraph of today\u2019s column. Instead of, \u201cWell, then you really blew it, didn\u2019t you?\u201d that sentence should read like this: \u201cThat\u2019s OK; after all, all the Windows PowerShell Week resources \u2013 including links to the on-demand webcasts, the question-and-answer logs, and other related goodies \u2013 are available on the <a href=\"http:\/\/null\/technet\/scriptcenter\/webcasts\/ps.mspx\"><b>Windows <\/b><b>PowerShell Week home page<\/b><\/a>.\u201d So we guess you\u2019re <i>not<\/i> out of luck after all.<\/p>\n<p>And yes, that does mean that you have to keep your job and spouse, at least for the moment. On the other hand, your dog probably <i>won\u2019t<\/i> bite you. And you can still have the opportunity to learn all about Windows PowerShell.<\/p>\n<p>Of course, one thing that you <i>won\u2019t<\/i> find on the Windows PowerShell Week home page is a script that can extract the text that appears between the string HOSTNAME= and a blank space in a line in a text file. But don\u2019t fret. Fortunately, we just happened to have a script lying around that can extract this kind of information from a string variable. We\u2019ll show you how this generic script works, then modify it slightly so that it can grab this same information from a text file.<\/p>\n<p>Here\u2019s the script:<\/p>\n<pre class=\"codeSample\">strSearchString = \"ABCDEFGHIJK, NDPSGW PORT=LPR HOSTNAME=R2333_HP_1100 ABCDEFGHIJK\"\nintStart = InStr(strSearchString, \"HOSTNAME=\")\nintStart = intStart + 9\nstrText = Mid(strSearchString, intStart, 250)\nFor i = 1 to Len(strText)\n    If Mid(strText, i, 1) = \" \" Then\n        Exit For\n    Else\n        strData = strData &amp; Mid(strText, i, 1)\n    End If\nNext\nWscript.Echo strData\n<\/pre>\n<p>As you noted in your email, B, your text file includes lines that look something like this:<\/p>\n<pre class=\"codeSample\">ABCDEFGHIJK, NDPSGW PORT=LPR HOSTNAME=R2333_HP_1100 ABCDEFGHIJK\n<\/pre>\n<p>You need to take these lines of code and find the string <i>HOSTNAME=<\/i>. Once you find this string you then want to grab all the text that appears after the equals sign, at least until you encounter a blank space. In this example, that means pulling out the text <b>R2333_HP_1100<\/b>. Let\u2019s see if we can figure out how to do that.<\/p>\n<table id=\"EEE\" 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>. Before we go much further we should probably point out that there are several different ways that we could tackle this chore; for example, we could have used regular expressions to locate the value in question. The approach we chose isn\u2019t necessarily the most sophisticated way of solving the problem, but we thought it was the easiest and most straightforward method; in addition, it was a method we thought the typical system administration scripter would be comfortable with. As usual, we\u2019re less concerned with elegance than we are with simply finding a way to get the job done.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>As you can see, we start out by assigning the sample line of text to a variable named strSearchString. We then use the <b>InStr<\/b> function in the following line of code to determine the starting position for the string <i>HOSTNAME=<\/i>:<\/p>\n<pre class=\"codeSample\">intStart = InStr(strSearchString, \"HOSTNAME=\")\n<\/pre>\n<p>In this case, the InStr function is going to return the value 30. Why? Because the string <i>HOSTNAME=<\/i> can be found at character position 30 in the string strSearchString (if you count the characters you\u2019ll see for yourself). Of course, knowing the starting position for <i>HOSTNAME=<\/i> is useful, but it doesn\u2019t quite solve our problem: we need to know where the string <i>ends<\/i>. Why? Because that\u2019s where we begin collecting data. Fortunately, that\u2019s an easy obstacle to overcome: <i>HOSTNAME=<\/i> has 9 characters in it, meaning that all we have to do is add 9 to the variable intStart and we\u2019ll know exactly where the target data begins. That\u2019s what we do with this line of code:<\/p>\n<pre class=\"codeSample\">intStart = intStart + 9\n<\/pre>\n<p>Like we said, now we know exactly where the data starts: in this case, that\u2019s character position 39 (30 + 9). (Admittedly, it might seem like the math is off by 1. But, again, count the number of characters and you\u2019ll see that this is OK.) Among other things, that tells us that we can discard the first 38 characters in the string; there\u2019s nothing in there of interest to us. With that in mind we use the following line of code to create a new string (stored in the variable strText) that starts at character 39 and encompasses the next 250 characters:<\/p>\n<pre class=\"codeSample\">strText = Mid(strSearchString, intStart, 250)\n<\/pre>\n<table id=\"EJF\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p><b>Note<\/b>. Why 250? Actually, that\u2019s an arbitrary number: we just wanted to make sure that we grabbed all the remaining characters in the string. And yes, we could have calculated the length of the string and determined <i>exactly<\/i> how many characters to grab, but we\u2019re assuming you won\u2019t have any line lengths larger than 250 characters. If you do, then you\u2019ll need to modify this line of code accordingly.<\/p>\n<p>And don\u2019t worry: if your string contains less than 250 characters this line of code won\u2019t generate an error. Instead, VBScript will simply take as many characters as <i>do<\/i> exist and call it good.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Next we set up a For Next loop that begins at 1 (representing the first character in the variable strText) and continues until we reach the end of the string (which we determine using the <b>Len<\/b> function):<\/p>\n<pre class=\"codeSample\">For i = 1 to Len(strText)\n<\/pre>\n<p>What are we going to do inside this loop? Well, for starters, we\u2019re going to check the very first character and see if it happens to be a blank space (remember, when we find a blank space we\u2019ve reached the end of our data). If character 1 <i>is<\/i> a blank space we call the <b>Exit For<\/b> command and exit the loop. If character 1 is <i>not<\/i> a blank space then we use the <b>Mid<\/b> function and this line of code to add the character to a variable named strData (in the parameters passed to Mid the variable <i>i<\/i> represents the letter in the string and the 1 tells Mid to grab only that one character):<\/p>\n<pre class=\"codeSample\">strData = strData &amp; Mid(strText, i, 1)\n<\/pre>\n<p>What does that mean? In this example, character 1 is the letter <i>R<\/i>. The letter <i>R<\/i> is not a blank space, so the value <i>R<\/i> gets added to strData. We then loop around and check the second character in the string: <i>2<\/i>. Again, this is not a blank space, so we append this character to strData, making strData equal to <i>R2<\/i>. We then loop around and check the third character in the string, continuing until we either run out of characters or until we encounter a blank space.<\/p>\n<p>After we exit the loop we then echo back the value of strData which, with any luck, should be this:<\/p>\n<pre class=\"codeSample\">R2333_HP_1100\n<\/pre>\n<p>And there you have it.<\/p>\n<p>Now, how would you go about doing this in a text file? Why, like this, of course:<\/p>\n<pre class=\"codeSample\">Const ForReading = 1\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(\"C:\\Scripts\\Test.txt\")\nDo Until objFile.AtEndOfStream\n    strData = \"\"\n    strSearchString = objFile.ReadLine\n    intStart = InStr(strSearchString, \"HOSTNAME=\")\n    If intStart &lt;&gt; 0 Then\n        intStart = intStart + 9\n        strText = Mid(strSearchString, intStart, 250)\n        For i = 1 to Len(strText)\n            If Mid(strText, i, 1) = \" \" Then\n                Exit For\n            Else\n                strData = strData &amp; Mid(strText, i, 1)\n            End If\n        Next\n    End If\n    Wscript.Echo strData\nLoop\n<\/pre>\n<p>We won\u2019t bother explaining the whys and wherefores of reading text files; we have plenty of <a href=\"http:\/\/null\/technet\/scriptcenter\/resources\/qanda\/textfiles.mspx\"><b>Hey, Scripting Guy! columns<\/b><\/a> that can help you with that. But now that you have the basic idea about how to locate the target information you shouldn\u2019t have too much trouble figuring out how the text file version of this script works.<\/p>\n<p>We hope that helps, B. And, again, if any of you missed Windows PowerShell Week don\u2019t worry: you can still revel in <a href=\"http:\/\/null\/technet\/scriptcenter\/webcasts\/ps.mspx\"><b>every minute of the week<\/b><\/a>. Is it true that, during the day 5 webcast, Peter Costantini sang not one but <i>two<\/i> Windows PowerShell songs? Let\u2019s put it this way: any time you hear<i> a story<\/i> about Peter, no matter how crazy, you should assume that it\u2019s true. <\/p>\n<p>But why not check out the day 5 webcast and see for yourself?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! In a text file, how can I extract the information that appears between the string HOSTNAME= and a blank space? &#8212; B Hey, B. You\u2019ll have to pardon us if we seem a little sluggish today; we\u2019re still recovering from all the fun and excitement of Windows PowerShell Week. What if you [&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":[40,3,4,14,5],"class_list":["post-66043","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-filesystemobject","tag-scripting-guy","tag-scripting-techniques","tag-text-files","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! In a text file, how can I extract the information that appears between the string HOSTNAME= and a blank space? &#8212; B Hey, B. You\u2019ll have to pardon us if we seem a little sluggish today; we\u2019re still recovering from all the fun and excitement of Windows PowerShell Week. What if you [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66043","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=66043"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66043\/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=66043"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=66043"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=66043"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}