Redirecting contents of a file to a variable in co

2019-08-05 12:18发布

问题:

I have a file "file.txt" which contains the output of "dir /s /b *.c"

I want to write this whole content of file.txt in a single variable .

Any ideas?

回答1:

The usual way to treat questions like this one is to reply: "What do you want this for?". However, your question is pure and simple, so here is the answer. The Batch file below not just store the contents of file.txt in a single variable, but it also later process the variable value as individual lines.

EDIT: I added the method to extract individual lines from the variable value as substrings.

@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

You must note that Batch variables can only store a maximum of 8K characters.



回答2:

No. But you can go through the lines one by one.

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

Maybe say what you are trying to achieve. Knowledge of C won't help you in batch because it's contary for historical reasons.



回答3:

You can use set /p:

set /p foo=<file.txt

See also this question.



回答4:

Batch-Script is a very limited tool with a primitive support for multi-line variables (with specific hacks that will not work as expected for this sceneario but if you are interested see this).

The only reasonable solution is to move to a capable language, which is every else less Batch-Script.