我有一个像这样的文件:
W X Y Z a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4
我想阅读每一行,然后生成如下结果:
W = a1 X = a2 Y = a3 z = a4 --------------- W = b1 X = b2 Y = b3 z = b4 --------------- W = c1 X = c2 Y = c3 z = c4
我正在尝试使用嵌套的for循环,但是它不起作用:
for /F "usebackq tokens=* delims= " %%A in ("%file%") do (
echo tushar
call echo %%A
我已经使用awk
在Unix中进行了相同的设置,并且运行良好。
答案 0 :(得分:0)
您的问题不仅是编码,还有背后的逻辑。
看看下面的代码;我插入了一些注释以显示正在执行的操作。
@echo off
setlocal enabledelayedexpansion
set "file=file.txt"
REM read every line...
set line=0
for /f "usebackq delims=" %%A in ("%file%") do (
set /a lines+=1
REM ... and tokenize it...
set count=0
for %%B in (%%A) do (
REM ... into an array.
set /a count+=1
set "Dta[!lines!-!count!]=%%B"
)
)
REM lines now holds the number of lines in the file, count is the number of tokens.
rem set Dta[
REM uncomment above line for troubleshooting (showing the array)
REM for every line [skip first line=Header]
for /l %%l in (2,1,%lines%) do (
REM for each token in the line
for /l %%t in (1,1,%count%) do (
REM echo Array[Header-Token] = Array[Line-Token]
echo !Dta[1-%%t]! = !Dta[%%l-%%t]!
)
REM insert delimiter line if it's not the last line:
if %%l lss %lines% echo -----------
)
有关延迟扩展的简短说明,请参见here。比您使用的call
方法更容易(和更快)。
答案 1 :(得分:0)
这是我要这样做的方式:
@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (test.txt) do (
set i=1
for %%b in (%%a) do (
if not defined header[!i!] (
set "header[!i!]=%%b"
) else (
for %%i in (!i!) do echo !header[%%i]! = %%b
)
set /A i+=1
)
echo ---------------
)
如果要消除其他虚线,则需要多几行代码...