1

我有一个 file.txt,其中包含安装在我的机器上的预言机的路径。从注册表示例中,此文件包含:

    ORACLE_HOME    REG_SZ    C:\oracle\product\11.2.0\dbhome_1
    ORACLE_HOME    REG_SZ    C:\oracle\product\11.2.0\dbhome_2

我想通过我的批处理文件将预言机的所有路径插入到列表或类似列表中。我怎样才能在批处理文件中做到这一点?谢谢!

4

2 回答 2

3

假设您想要内存中的值“列表”,而不是文件中:

我认为大多数人更喜欢可以通过索引值访问的值“数组”。(注意 - 批处理没有正式的数组,但可以模拟它们)。

只要没有主路径包含!. 如果包含并启用延迟扩展,扩展%%B将损坏。!

@echo off
setlocal enableDelayedExpansion

:: Read the file and create an "array" of home paths
:: This will fail if any of the paths contain !
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
  set /a cnt+=1
  set "home.!cnt!=%%B"
)

:: Access the "array" members
for /l %%N in (1 1 %cnt%) do echo !home.%%N!

您可能可以在许多环境中运行上述代码多年,并且永远不会遇到问题。但是某个地方的某个人可能包含!在 Oracle 主路径中。有许多策略可以解决上述问题!。以下是三个选项:

选项 1 - 代码量最少,但由于 CALL 最慢

@echo off
setlocal disableDelayedExpansion

:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
  set /a cnt+=1
  call set "home.%%cnt%%=%%B"
)

:: Access the "array"
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!

选项 2 - 一种使用 FINDSTR 计算行数的有趣且有效的方法。

@echo off
setlocal disableDelayedExpansion

:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "tokens=1,3* delims=: " %%A in ('findstr /n "^" "file.txt"') do (
  set "home.%%A=%%C"
  set "cnt=%%A"
)

:: Access the "array" members
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!

选项 3 - 一种使用延迟扩展切换的有效方法,但代码最多

@echo off
setlocal disableDelayedExpansion

:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
  set /a cnt+=1
  setlocal enableDelayedExpansion
  for %%N in (!cnt!) do (
    endlocal
    set "home.%%N=%%B"
  )
)

:: Access the "array"
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!

也可以在单个变量中包含主路径列表。每个路径都应该用引号括起来。路径可以用空格、逗号、分号、等号或制表符分隔。我选择了空间。

列表的大小是有限的,因为批处理环境变量的最大大小约为 8191 字节。由于 CALL,此解决方案也相对较慢。这些问题在现实世界中都不太可能成为问题。

@echo off
setlocal disableDelayedExpansion

:: Read the file and create a space delimited list of quoted home paths
:: This will safely process all paths, regardless of value
for /f "usebackq tokens=2*" %%A in ("file.txt") do (call set list=%%list%% "%%~B")

:: optional - remove leading space
(set list=%list:~1%)

:: Display the list
echo list=%list%

:: Access the list members
for %%F in (%list%) do echo %%~F
于 2012-12-10T11:24:55.297 回答
0
for /f "tokens=3 delims= " %%a in (file.txt) do echo %%a >>paths.txt
于 2012-12-10T11:08:03.347 回答