问题
I have a file named 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
I need to retrieve Index
number corresponding to "c:\" and then subtract it minus 1 to get Index
for the entire disk.
Any ideas ?
回答1:
Try next array-like approach:
@ECHO OFF >NUL
SETLOCAL enableextensions enabledelayedexpansion
set /A "ii=-1"
For /F "usebackq tokens=1* delims=:" %%G in (
"D:\bat\StackOverflow\files\30435794.txt") do (
if /I "%%~G"=="Index" set /A "ii+=1"
For /F "tokens=*" %%# in ("%%~H") do set "auxH=%%~#"
set "__%%~G[!ii!]=!auxH!"
if /I "!auxH!"=="C:\" set /A "__indexC=!ii!-1"
)
set __ | findstr /I /L "[%__indexC%]"
ENDLOCAL
goto :eof
Output:
==>D:\bat\StackOverflow\30435794.bat
__Device Name[0]=\Device\Harddisk0\Partition0
__Drive[0]=entire disk
__Index[0]=0
__Size[0]=55.899GB
__Type[0]=Harddisk
==>
Resources (required reading):
- (command reference) An A-Z Index of the Windows CMD command line
- (additional particularities) Windows CMD Shell Command Line Syntax
- (
%~G
etc. special page) Command Line arguments (Parameters) - (special page) EnableDelayedExpansion
回答2:
@echo off
setlocal
set "Index="
for /F "tokens=2" %%a in ('findstr "Index: Drive:" hdd_list.txt') do (
if not defined Index (
set /A Index=%%a-1
) else (
if /I "%%a" equ "C:\" (
goto diskFound
) else (
set "Index="
)
)
)
:diskFound
echo The index for entire disk C:\ is: %Index%
回答3:
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"
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).
The search looks for the Index line, capturing the number, followed by any line, followed by the Drive: C\
line.
来源:https://stackoverflow.com/questions/30435794/find-string-in-text-file-and-set-variable-with-windows-batch