从批处理文本中提取字符串

时间:2015-04-20 14:45:53

标签: batch-file automation

我正在研究一个自动化项目:完成我留下的这个难题。

我有一个文件(com.txt):

AUX = \DosDevices\1
1 = \Device\Serial0
10 = \Device\VCP0
7 = \Device\Silabser0
8 = \Device\Silabser1

我需要使用批处理读取此文件并创建3个变量: 寻找“Silabser0”并将“7”插入var 寻找“Silabser1”并将“8”插入var 并查找“VCP0”并将“10”插入var (这些数字在不同文件之间变化,但Silabser0 / 1和VCP0是永久性的)

输出npocmaka:

C:\Users\Test\Desktop>set file_loc=c:\COMports.txt

C:\Users\Test\Desktop>for /F "usebackq tokens=1 delims== " %a in ("c:\COMports.t
xt") do (for /F "tokens=2 delims=\" %x in ("%b") do set %x=%a )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=AUX )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=1 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=10 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=7 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=8 )

C:\Users\Test\Desktop>echo
ECHO is on.

C:\Users\Test\Desktop>echo
ECHO is on.

C:\Users\Test\Desktop>echo
ECHO is on.

2 个答案:

答案 0 :(得分:1)

未测试(假设路径始终有两个分隔符 - \

@echo off

set file_loc=vals.txt

for /f "usebackq tokens=1* delims== " %%a in ("%file_loc%") do (
   for /f "tokens=2 delims=\" %%x in ("%%b") do set %%x=%%a
)

echo %Serial0%
echo %VCP0%
echo %Silabser0%
echo %Silabser1%

答案 1 :(得分:0)

iv编辑文件看起来像:

FileStream stream = File.Open(FilePath,FileMode.OpenOrCreate);            
                   if (null != stream)
                   {
                       byte[] encrypted_data=something; // your bytes
                       foreach (byte b in encrypted_data)
                       {
                           stream.WriteByte(b);
                       }
                   }
stream.Close();

然后使用:

AUX\DosDevices\1
1\Device\Serial0
10\Device\VCP0
7\Device\Silabser0
8\Device\Silabser1