将文件输出存储到变量中

发布于 2024-10-10 02:49:23 字数 298 浏览 0 评论 0原文

我想将文本文件的输出存储到一个变量中,这样我就可以将整个文件作为参数传递。

我使用的是 Windows 2003 Server。

文本文件有多行,例如:

10.20.210.100 fish
10.20.210.101 rock

我正在使用:

Set /P var=<file.txt

它仅读取文件的第一行。

我也尝试使用 FOR 循环,但它只将最后一行分配给变量。

I want to store the output of text file into a variable, so I can pass the whole file as parameter.

I am using Windows 2003 Server.

The text files have multiple lines like:

10.20.210.100 fish
10.20.210.101 rock

I was using:

Set /P var=<file.txt

It reads only the first line of the file.

I tried with FOR loop also but it assigned only the last line to the variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷迭香的记忆 2024-10-17 02:49:23

没有一种简单的方法可以将文件的完整内容放入一个变量中。
变量的长度限制为 ~8100。
将 CR/LF 放入变量中很复杂,

但是使用 FOR 循环,您可以获得每一行。

尝试查看批处理脚本逐行读取

编辑:
要获取单个变量中的每一行,您可以使用它

@echo off
SETLOCAL EnableDelayedExpansion
set n=0
for /f "delims=" %%a IN (example.txt) do (
  set /a n+=1
  set "line[!n!]=%%a"
  echo line[!n!] is '%%a'
)
set line

或仅获取一个变量中的所有内容(不带 CR/LF)

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
  set "line=!line! %%a"
)
echo !line!

There is no simple way to get the complete content of a file into one variable.
A variable has a limit of ~8100 length.
And it is complicated to get CR/LF into a variable

But with a FOR-loop you can get each single line.

Try a look at batch script read line by line

EDIT:
To get each line in a single variable you can use this

@echo off
SETLOCAL EnableDelayedExpansion
set n=0
for /f "delims=" %%a IN (example.txt) do (
  set /a n+=1
  set "line[!n!]=%%a"
  echo line[!n!] is '%%a'
)
set line

or to get all in only one variable (without CR/LF)

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
  set "line=!line! %%a"
)
echo !line!
安静被遗忘 2024-10-17 02:49:23

Jeb 的脚本运行完美,但是如果您 echo %line% 它包含文件时间中的每一行。如果你使用 echo !Line! ,它包含一行!也与其他线路。我对脚本做了一些修改,现在得到了预期的结果。

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
set "line1=%%a"
set "line=!line1! and  %%a"
)
echo !line!

或者

echo %line%

现在您将在机器人案例中得到相同的结果。

Jeb’s script is working perfect, But if you echo %line% it contains each line no of line in file times. And if you use echo !Line! ,it contain one !line! also with other line. I did a little modification in script and now I am getting expected result.

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
set "line1=%%a"
set "line=!line1! and  %%a"
)
echo !line!

or

echo %line%

Now you will get same result in bot cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文