将每行的txt文件读入一个数组,然后在数组中读取每个条目

时间:2016-11-07 15:36:39

标签: arrays windows batch-file

我目前正在尝试使用cmd来读取我使用PowerShell创建的批处理文件。这个文件中的每一行都是一个目录,所以我希望能够创建一个读取每一行的循环; dir目录并将输出存储在文本文件中。

到目前为止,我对如何做到这一点的想法是使用:

set Lines=TYPE Z:\archive\%username%.txt | FIND "" /v /c

要查找文件中的行数,并使用Do until i = Lines来指定每行。

如何将.txt文件中的每一行添加到一个数组中,以便我可以将它们添加进去?最重要的是,如何将其输出到.txt文件?

2 个答案:

答案 0 :(得分:1)

其他语言中有许多概念无法直接转换为Windows批处理。

批处理文件没有任何固有的数组概念。可以通过巧妙使用变量名来模拟它们,但这里不需要。

此外,您不能简单地将命令的结果分配给环境变量,就像在'nix shell中一样。您可以使用for /f "delims=" %%A in ('someCommand') do REM Do something with the line of output contained within %%A之类的内容迭代命令的每一行输出。例如,您可以构建值的“数组”。但同样,这里不需要处理命令的结果,更不用说构建数组了。

FOR / F命令是一个复杂的野兽,可以做很多事情,具体取决于使用的语法。其中一项功能是迭代文件的行。所以你的解决方案就像:

for /f "usebackq eol=: delims=" %%F in ("Z:\archive\%username%.txt") do dir "%%F"

如果直接从控制台运行命令,而不是从批处理脚本中运行,则 然后每个%%F必须成为%F

答案 1 :(得分:0)

试试这个解决方案:

@echo off
Title Display recursively all Folders using Array
SET "Count=0"
set "Folder=%userprofile%\Desktop"
set "ListFolders=%~dp0ListFolders.txt"
If Exist %ListFolders% Del %ListFolders%
Dir /b /s /a:d "%folder%" >> %ListFolders%
setLocal EnableDelayedExpansion
REM Populate the array with existent sub-folders in this folder
for /f "tokens=* delims= " %%a in ('Type "%ListFolders%"') do (
    set /a Count+=1
    set "Folder[!Count!]=%%~na"
    set "ListpathFolder[!Count!]=%%~fa"
)
::********************************************************
:Display_Folders
cls & color 0B
echo wscript.echo Len("%Folder%"^) + 20 >"%tmp%\length.vbs"
for /f %%a in ('Cscript /nologo "%tmp%\length.vbs"') do ( set "cols=%%a")
If %cols% LSS 50 set /a cols=%cols% + 24
set /a lines=%Count% + 17
Mode con cols=%cols% lines=%lines%
echo(
echo  ------------------------------------------------ 
ECHO   Folder : "%Folder%"
echo  ------------------------------------------------
rem Display array elements
for /L %%i in (1,1,%Count%) do (
    echo [%%i] - "!Folder[%%i]!"
)
echo(
echo Total number in "%Folder%" is %Count%
echo(
echo "Type the number of folder that you want to explore"
set /p "Input="
For /L %%i in (1,1,%Count%) do (
    If "%INPUT%" EQU "%%i" (
        Call :Explorer "!ListpathFolder[%%i]!"
        cls
        Dir "!ListpathFolder[%%i]!" 
        echo(
        echo Hit any key to show again all folders ...
        pause>nul
    )
)
Goto Display_Folders
::*********************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::*********************************************************
相关问题