{"id":7003,"date":"2012-07-31T07:00:00","date_gmt":"2012-07-31T07:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/2012\/07\/31\/reading-the-output-of-a-command-into-a-batch-file-variable\/"},"modified":"2012-07-31T07:00:00","modified_gmt":"2012-07-31T07:00:00","slug":"reading-the-output-of-a-command-into-a-batch-file-variable","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20120731-00\/?p=7003","title":{"rendered":"Reading the output of a command into a batch file variable"},"content":{"rendered":"<p>\nIt&#8217;s Day Two of Batch File Week.\nDon&#8217;t worry, it&#8217;ll be over in a few days.\n<\/p>\n<p>\nThere is no obvious way to read the output of a command\ninto a batch file variable.\nIn unix-style shells, this is done via backquoting.\n<\/p>\n<pre>\nx=`somecommand`\n<\/pre>\n<p>\nThe Windows command processor does not have direct backquoting,\nbut you can fake it by abusing the <code>FOR<\/code> command.\nHere&#8217;s the evolution:\n<\/p>\n<p>\nThe <code>\/F<\/code> flag to the <code>FOR<\/code> command says\nthat it should open the file you pass in parentheses and set\nthe loop variable to the contents of each line.\n<\/p>\n<pre>\nfor \/f %%i in (words.txt) do echo [%%i]\n<\/pre>\n<p>\nThe loop variable in the <code>FOR<\/code> command takes one\npercent sign if you are executing it directly from the command prompt,\nbut two percent signs if you are executing it from a batch file.\nI&#8217;m going to assume you&#8217;re writing a batch file, so if you want\nto practice from the command line, remember to collapse the double\npercent signs to singles.\n<\/p>\n<p>\nI&#8217;m cheating here because I know that <code>words.txt<\/code>\ncontains one word per line.\nBy default,\nthe <code>FOR<\/code> command sets the loop variable to the first\nword of each line.\nIf you want to capture the entire line, you need to change the delimiter.\n<\/p>\n<pre>\nfor \/f \"delims=\" %%i in (names.txt) do echo [%%i]\n<\/pre>\n<p>\nThere are other options for capturing say the first and third word\nor whatever.\nSee the <code>FOR \/?<\/code> online help for details.\n<\/p>\n<p>\nNow, parsing files is not what we want, but it&#8217;s closer.\nYou can put the file name in single quotes\nto say &#8220;Instead of opening this file and reading the contents,\nI want you to run this <i>command<\/i> and read the contents.&#8221;\nFor example, suppose you have a program called\n<code>printappdir<\/code> which outputs a directory,\nand you want a batch file that changes to that directory.\n<\/p>\n<pre>\nfor \/f \"delims=\" %%i in ('printappdir') do cd \"%%i\"\n<\/pre>\n<p>\nWe ask the <code>FOR<\/code> command to run the <code>printappdir<\/code>\nprogram and execute the command <code>cd \"%%i\"<\/code> for each\nline of output.\nSince the program has only one line of output,\nthe loop executes only once, and the result is that the directory\nis changed to the path that the\n<code>printappdir<\/code> program prints.\n<\/p>\n<p>\nIf you want to capture the output into a variable,\njust update the action:\n<\/p>\n<p><pre>\nfor \/f %%i in ('printappdir') do set RESULT=%%i\necho The directory is %RESULT%\n<\/pre>\n<p>\nIf the command has multiple lines of output, then this will\nend up saving only the last line, since previous lines get\noverwritten by subsequent iterations.\n<\/p>\n<p>\nBut what if the line you want to save isn&#8217;t the last line?\nOr what if you don&#8217;t want the entire line?\n<\/p>\n<p>\nIf the command has multiple lines of output and you&#8217;re interested\nonly in a particular one,\nyou can filter it in the <code>FOR<\/code> command itself&#8230;\n<\/p>\n<pre>\nfor \/f \"tokens=1-2,14\" %%i in ('ipconfig') do <a HREF=\"http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2008\/08\/06\/8835317.aspx\">^<\/a>\n    if \"%%i %%j\"==\"IPv4 Address.\" set IPADDR=%%k\n<\/pre>\n<p>\nThe above command asked to execute the\n<code>ipconfig<\/code> command and extract the first,\nsecond, and fourteenth words into loop variable\nstarting with <code>%i<\/code>.\nIn other words,\n<code>%i<\/code> gets the first word,\n<code>%j<\/code> gets the second word,\nand\n<code>%k<\/code> gets the fourteenth word.\n(Exercise: What if you want to extract more than 26 words?)\n<\/p>\n<p>\nThe loop then checks each line to see if it begins\nwith &#8220;<tt>IPv4 Address.<\/tt>&#8220;,\nand if so, it saves the fourteenth word (the IP address itself)\ninto the <code>IPADDR<\/code> variable.\n<\/p>\n<p>\nHow did I know that the IP address was the fourteenth word?\nI counted!\n<\/p>\n<pre>\n   IPv4 Address. . . . . . . . . . . : 192.168.1.1\n   ---- -------- - - - - - - - - - - - -----------\n     1      2    3 4 5 6 7 8 9  11  13      14\n                              10  12\n<\/pre>\n<p>\nThat&#8217;s also why my test includes the period after\n<tt>Address<\/tt>:\nThe first dot comes right after the word <tt>Address<\/tt>\nwithout an intervening space, so it&#8217;s considered part of the\nsecond &#8220;word&#8221;.\n<\/p>\n<p>\nSomebody thought having the eye-catching dots would look pretty,\nbut didn&#8217;t think about how it makes parsing a real pain in the butt.\n(Note also that the above script works only for US-English systems,\nsince the phrase <tt>IPv4 Address<\/tt> will change based on your\ncurrent language.)\n<\/p>\n<p>\nInstead of doing the searching yourself,\nyou can have another program do the filtering,\nwhich is important if the parsing you want is\nbeyond the command prompt&#8217;s abilities.\n<\/p>\n<pre>\nfor \/f \"tokens=14\" %%i in ('ipconfig ^| findstr \/C:\"IPv4 Address\"') do ^\n  set IPADDR=%%i\n<\/pre>\n<p>\nThis alternate version makes the findstr<\/code> program do the\nheavy lifting, and then saves the fourteenth word.\n(But this version will get fooled by the line\n<tt>Autoconfiguration IPv4 Address<\/tt>.)\n<\/p>\n<p>\n<b>Yes I know<\/b>\nthat you can do this in PowerShell\n<\/p>\n<pre>\nforeach ($i in Get-WmiObject Win32_NetworkAdapterConfiguration) {\n  if ($i.IPaddress) { $i.IPaddress[0] }\n}\n<\/pre>\n<p>\nYou&#8217;re kind of missing the point of Batch File Week.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It&#8217;s Day Two of Batch File Week. Don&#8217;t worry, it&#8217;ll be over in a few days. There is no obvious way to read the output of a command into a batch file variable. In unix-style shells, this is done via backquoting. x=`somecommand` The Windows command processor does not have direct backquoting, but you can fake [&hellip;]<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-7003","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>It&#8217;s Day Two of Batch File Week. Don&#8217;t worry, it&#8217;ll be over in a few days. There is no obvious way to read the output of a command into a batch file variable. In unix-style shells, this is done via backquoting. x=`somecommand` The Windows command processor does not have direct backquoting, but you can fake [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/7003","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=7003"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/7003\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=7003"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=7003"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=7003"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}