windows - 将文件内容重定向到命令提示符中的变量

标签 windows batch-file cmd

我有一个文件“file.txt”,其中包含“dir/s/b *.c”的输出

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

有什么想法吗?

最佳答案

处理此类问题的通常方式是回答:“你想要这个干什么?”。但是,您的问题很简单,所以这里就是答案。下面的批处理文件不仅将 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 个字符。

关于windows - 将文件内容重定向到命令提示符中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573571/

相关文章:

windows - Pango-WARNING ** : couldn't load font ouldn't load font "Times Not-Rotated 18", 回落到 "Sans Not-Rotated 10px",期待丑陋的输出

java - Ant 无法删除 Windows 上的某些文件

batch-file - 我将如何编写一个批处理文件来在整个目录上运行 ffmpeg 命令?

batch-file - cmd 不支持 UNC 路径作为当前目录 pushd

windows - cmd 有效,但 C :\Windows\System32\cmd. exe 无效

java - 如何在没有 Eclipse 的情况下运行 selenium 代码?

c# - 在特定屏幕上启动进程

windows - Windows/OSX/类 Unix 和二进制文件的 Gnome glib 状态

batch-file - 如何在 for/F 循环内设置变量

Python:在 git-bash 环境中运行 python 脚本