需要使用批处理从字符串中获取所需的数据

时间:2015-07-29 12:22:23

标签: batch-file string-split

我需要在给定字符串中仅提取URL和app id并保存在变量

  

url:{“url”:“ad.ifwcash.com/www/delivery/afr.php?zoneid=127&cb=2015738640”,“app”:61}

最终结果如

variable_1 : ad.ifwcash.com/www/delivery/afr.php?zoneid=127&cb=2015738640

variable_2 : 61

2 个答案:

答案 0 :(得分:1)

如果同一目录中的url.txt文件包含内容,则此方法有效: {"url":{ "url":"ad.ifwcash.com/www/delivery/afr.php?zoneid=127&cb=2015738640", "app":61}} 最后,您需要在第三行更改文件的名称/位置(保存下面带有.bat扩展名的文件):

@echo off

setlocal enableDelayedExpansion

set "jsonFile=.\url.txt"
set counter=1



for /f %%# in ('echo %jsonFile%^|mshta.exe "%~f0"') do (
  set "variable_!counter!=%%#"
  set /a counter=counter+1
)

set variable_

echo #############################
echo ###  more batch code here ###
echo #############################


exit /b

<HTA:Application
   ShowInTaskbar = no
   WindowsState=Minimize
   SysMenu=No
   ShowInTaskbar=No
   Caption=No
   Border=Thin
>
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<script language="javascript" type="text/javascript">
    window.visible=false;
    window.resizeTo(1,1);

   var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
   var fso2= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0);
   var json=fso2.ReadLine();

   var fso3=new ActiveXObject("Scripting.FileSystemObject");

   var file = fso3.OpenTextFile(json, 1);

    var strText = file.ReadAll();
    file.Close();

   var obj = JSON.parse(strText)

   fso.Write(obj.url.url + "\r\n" + obj.url.app + "\r\n");
   window.close();
</script>

答案 1 :(得分:1)

这是使用JScript的另一种混合解决方案。 (仍以.bat扩展名保存。)

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "JSONfile=test.json"

for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%JSONfile%"') do set "%%~I"

setlocal enabledelayedexpansion
echo URL: !url!
echo App: !app!
endlocal

goto :EOF

@end // end batch / begin JScript chimera

var fso = WSH.CreateObject('scripting.filesystemobject'),
    JSONfile = fso.OpenTextFile(WSH.Arguments(0), 1);

eval('obj = {' + JSONfile.ReadAll() + '}');
JSONfile.Close();

function walk(tree) {
    for (var i in tree) {
        if (typeof tree[i] === 'object') walk(tree[i]);
        else WSH.Echo(i + '=' + tree[i]);
    }
}

walk(obj);

输出:

  

网址:ad.ifwcash.com/www/delivery/afr.php?zoneid=127&cb=2015738640
  应用程序:61

延迟扩展用于防止对网址中的&进行评估。

如果您不控制JSON的生成,请参阅this big fat warning