我在文本文件中有信息需要提取并放入循环中。为简单起见,我们假设第一行是一个人,第二行是他们最喜欢的颜色。
文本文件如下所示:
tim red sarah blue and yellow sam green
我希望回声输出看起来像这样:
tim likes red
sarah likes blue and yellow
sam likes green
到目前为止我的代码内容如下:
for /f "tokens=1 delims=" %%Name %%color in (C:\textfile.txt) do echo %%Name likes %%color
答案 0 :(得分:0)
@echo off
setlocal enabledelayedexpansion
set x=0
for /f "delims=" %%a in (t.txt) do (
set /a "x=(x+1) %% 2"
if !x! == 1 set name=%%a
if !x! == 0 echo !name! likes %%a.
)
答案 1 :(得分:0)
对于您的任务,我看到以下选项:
使用for /F
循环并在每隔一次迭代期间交替设置和清除变量(NAME
)以等待与某个名称关联的颜色:
@echo off
setlocal EnableDelayedExpansion
set "NAME="
for /F "usebackq tokens=*" %%L in ("textfile.txt") do (
if defined NAME (
echo !NAME! likes %%L
set "NAME="
) else (
set "NAME=%%L"
)
)
endlocal
使用for /L
循环预先确定行数的一半,并使用输入重定向(<
)每次迭代一次读取两行:
@echo off
setlocal EnableDelayedExpansion
for /F %%C in ('^< "textfile.txt" find /C /V ""') do set /A "HALF=%%C/2"
< "textfile.txt" (
for /L %%I in (1,1,%HALF%) do (
set /P NAME=
set /P COLOUR=
echo !NAME! likes !COLOUR!
)
)
endlocal