【问题标题】:Manipulating strings in arrays in a batch file?在批处理文件中操作数组中的字符串?
【发布时间】:2017-04-20 06:26:08
【问题描述】:

我目前有一个批处理文件,它正在遍历一个文本文件并将每一行分配到一个数组中。我想遍历循环并从数组中的每个值中删除一定数量的字符。这可以吗?

@ECHO off

findstr /C:"number" /C:"type" testFile.txt > oneresult.txt
set "file=oneresult.txt"
set /A i=0
timeout /t 1
echo ---------------Results--------------- > results.txt
for /f "tokens=*" %%x in (oneresult.txt) do (
call echo %%x >> results.txt
call set array[%i%]=%%x
set /A i+=1
)

call echo  %i% files received >> results.txt
del "oneresult.txt"

所以现在它只是打印从 testFile.txt 中检索到的字符串,然后最终将它们放入 result.txt。我希望来自 testFile.txt 的所有字符串都删除前 10 个字符。如果有更简单的方法请告诉我。到目前为止,这就是我所发现的,但我也是一个批次的菜鸟。

只是在没有数组的情况下弄清楚了,并将答案发布给将来可能正在搜索的任何其他人:

@ECHO off

findstr /C:"number" /C:"type" testFile.txt > oneresult.txt
set /A i=0
timeout /t 1
echo ---------------Results--------------- > results.txt

for /f "tokens=*" %%x in (oneresult.txt) do (
setlocal enabledelayedexpansion
call set print=%%x
call set newprint=!print:~32!
call echo !newprint! >>results.txt 
endlocal
set /A i+=1
)

call echo  %i% files received >> results.txt
del "oneresult.txt"

【问题讨论】:

  • 批处理文件中的所有阵列管理详细信息在this answer 进行了解释。例如:set array[!i!]=%%xfor %%i in (!i!) do echo !array[%%i]:~32!

标签: batch-file window


【解决方案1】:
  • 您在代码中使用了多个调用,却没有理解这些pseudo calls 通常用于不同类型的延迟扩展,不需要setlocal enabledelayedexpansion,而是将百分号加倍。
  • 中间文件 oneresult 不是必需的,一个用于 /f 解析 findstr 输出的文件就足够了。
  • 包含所有输出行的一组括号可以重定向到 results.txt

@ECHO off
set /A i=0
(
  echo ---------------Results---------------
  for /f "tokens=*" %%x in (
    'findstr /C:"number" /C:"type" testFile.txt'
  ) do (
    set print=%%x
    call echo:%%print:~32%%
    set /A i+=1
  )
  call echo %%i%% files received
) > results.txt 

下面带有setlocal enabledelayedexpansion的代码功能相同

@ECHO off&Setlocal EnabledelayedExpansion
set /A i=0
(
  echo ---------------Results---------------
  for /f "tokens=*" %%x in (
    'findstr /C:"number" /C:"type" testFile.txt'
  ) do (
    set print=%%x
    echo:!print:~32!
    set /A i+=1
  )
  echo !i! files received
) > results.txt 

【讨论】:

  • @N. Spivs 只是出于兴趣,您首先检查了我的答案,现在未检查:我的批次有任何问题还是您还有其他问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 2011-02-15
相关资源
最近更新 更多