在文本文件中查找字符串并使用Windows Batch设置变量 [英] Find string in text file and set variable with windows batch

查看:158
本文介绍了在文本文件中查找字符串并使用Windows Batch设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为hdd_list.txt的文件.

Index: 0
Device Name: \Device\Harddisk0\Partition0
Drive: entire disk
Label: 
Type: Harddisk
Size: 55.899GB

Index: 1
Device Name: \Device\Harddisk0\Partition1
Drive: C:\
Label: 
Type: Harddisk
Size: 55.897GB

Index: 2
Device Name: \Device\Harddisk1\Partition0
Drive: entire disk
Label: 
Type: Harddisk
Size: 465.761GB

Index: 3
Device Name: \Device\Harddisk1\Partition1
Drive: E:\
Label: Backup
Type: Harddisk
Size: 465.758GB

我需要检索与"c:\"相对应的Index数字,然后减去它减去1,以得到整个磁盘的Index.

I need to retrieve Index number corresponding to "c:\" and then subtract it minus 1 to get Index for the entire disk.

有什么想法吗?

推荐答案

我会使用 JREPL.BAT -一个纯脚本(混合JScript/批处理)正则表达式文本处理实用程序,可从XP开始在任何Windows计算机上本地运行.

I would use JREPL.BAT - a pure script (hybrid JScript/batch) regular expression text processing utility that runs natively on any Windows machine from XP onward.

@echo off
for /f %%N in (
  'jrepl "Index: (\d+)\r?\n.*\nDrive: C:\\" "$1-1" /jmatch /m /f hdd_list.txt'
) do set "index=%%N"

我使用/M选项允许跨多行搜索,并且使用/JMATCH选项仅返回匹配项,并将替换字符串指定为JScript表达式(从值中减去1).

I use the /M option to allow searches across multiple lines, and the /JMATCH option to only return matches, and to specify the replacement string as a JScript expression (subtract 1 from the value).

搜索将查找索引行,并捕获数字,然后是任意行,然后是Drive: C\行.

The search looks for the Index line, capturing the number, followed by any line, followed by the Drive: C\ line.

这篇关于在文本文件中查找字符串并使用Windows Batch设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆