在命令提示符下将文件的内容重定向到变量

时间:2015-04-11 02:59:54

标签: windows batch-file cmd

我有一个文件" file.txt"其中包含" dir / s / b * .c"

的输出

我想将file.txt的整个内容写在一个变量中。

有什么想法吗?

4 个答案:

答案 0 :(得分:5)

处理像这样的问题的常用方法是回复:"你想要这个是什么?"。但是,你的问题是纯粹而简单的,所以这就是答案。下面的批处理文件不仅将file.txt的内容存储在单个变量中,而且稍后还将变量值作为单独的行处理。

编辑:我添加了从变量值中提取单个行作为子串的方法。

@echo off
setlocal EnableDelayedExpansion

rem Create variables with LF and CR values:
set LF=^
%empty line 1/2, don't remove%
%empty line 2/2, don't remove%
for /F %%a in ('copy /Z "%~F0" NUL') do set CR=%%a

rem Store the contents of file.txt in a single variable,
rem end each line with <CR><LF> bytes
set "variable="
for /F "delims=" %%a in (file.txt) do (
   set "variable=!variable!%%a!CR!!LF!"
)

rem 1- Show the contents of the variable:
echo !variable!

rem 2- Process the contents of the variable line by line
echo/
set i=0
for /F "delims=" %%a in ("!variable!") do (
   set /A i+=1
   echo Line !i!- %%a
)

rem Get the starting position and length of each line inside the variable
set /A i=0, lastStart=0
for /F "delims=:" %%a in (
      '(cmd /V:ON /C set /P "=^!variable^!" ^& echo/^) ^<NUL ^| findstr /O "^^"'
   ) do (
   set /A len[!i!]=%%a-lastStart-2, i+=1
   set /A start[!i!]=%%a, lastStart=%%a
)
set "len[0]="
set "start[%i%]="
set /A lastLine=i-1

rem 3- Extract individual lines from the variable contents as substrings
:getNumber
   echo/
   set "num="
   set /P "num=Enter line number (nothing to end): "
   if not defined num goto end
   if %num% gtr %lastLine% echo Invalid number & goto getNumber
   for /F "tokens=1,2" %%i in ("!start[%num%]! !len[%num%]!") do (
      echo Line %num%- !variable:~%%i,%%j!
   )
goto getNumber
:end

您必须注意,批处理变量最多只能存储8K个字符。

答案 1 :(得分:1)

没有。但是你可以逐个查看这些内容。

for /f "delims=" %A in (file.txt) do echo %A

也许说出你想要实现的目标。由于历史原因,对C的了解不会对你有所帮助。

答案 2 :(得分:1)

您可以使用set / p:

set /p foo=<file.txt

另见this question

答案 3 :(得分:1)

批处理脚本是一个非常有限的工具,它具有对多行变量的原始支持(特定的黑客攻击无法按照此场景的预期工作,但如果您感兴趣 {{ 3}} )。

唯一合理的解决方案是转移到一种功能强大的语言,而不是批处理脚本