在命令提示符下将文件内容重定向到变量 [英] Redirecting contents of a file to a variable in command prompt

查看:144
本文介绍了在命令提示符下将文件内容重定向到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想写出以下内容:

有什么想法吗?

推荐答案

处理这种问题的通常方法是回答:您想要这个做什么?。但是,您的问题很简单,所以这里是答案。下面的批处理文件不仅将file.txt的内容存储在单个变量中,而且以后还会将变量值作为单独的行进行处理。

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 :我添加了从变量值中提取各个行作为子字符串的方法。

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

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

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

这篇关于在命令提示符下将文件内容重定向到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆