【问题】将文档内容横列变为纵列
a.txt内容如下:
a b c d e f
h i j k l m n
1 2 3 4 5
6 7 8 9 10 11 12 13 14 15
a s d
11 12 13 14 15
要求输出结果如下:
a h 1 6 a 11
b i 2 7 s 12
c j 3 8 d 13
d k 4 9 14
e l 5 10 15
f m 11
n 12
13
14
15
【方法1】效率是比较低的了- @echo off
- for /f "delims=" %%i in (test.txt) do (
- set /a n+=1
- call set "str%%n%%=%%i "
- )
-
- for /l %%i in (1 1 10) do call :join
- pause>nul
-
- :split obj
- call set "var=%%%1%%"
- if "%var%"=="" set "str=" &goto :eof
- for %%i in (%var%) do (
- set "str=%%i"
- call set "%1=%%var:* =%%"
- goto :eof
- )
-
- :join
- set "tmp="
- for /l %%i in (1 1 %n%) do (
- call :split str%%i
- call set tmp=%%tmp%% %%str%%
- )
- echo.%tmp%
复制代码 【方法2】来段效率高点的代码,通过构造数组来实现,没有考虑特殊情况:- @echo off
- :: 注意: set /p= 语句<nul前的空格是跳格键,在论坛中会被转换为空格
- :: 复制下来之后,请重新手工设置跳格,否则,将不能起到对齐的效果。
- set /a num=0,_num=0,max=0
- setlocal enabledelayedexpansion
- for /f "delims=" %%i in (test.txt) do (
- set /a num+=1,_num=0
- for %%j in (%%i) do (
- set /a _num+=1
- set str!num!_!_num!=%%j
- if !_num! geq !max! set max=!_num!
- )
- )
- for /l %%i in (1,1,%max%) do (
- for /l %%j in (1,1,%num%) do (
- set /p=!str%%j_%%i! <nul
- )
- echo.
- )
- pause
复制代码 【方法3】借用namejm的代码解决对齐的问题:- @echo off
- set /a num=0,_num=0,max=0
- setlocal enabledelayedexpansion
- for /f "delims=" %%i in (test.txt) do (
- set /a num+=1,_num=0
- for %%j in (%%i) do (
- set /a _num+=1
- set str!num!_!_num!=%%j
- if !_num! geq !max! set max=!_num!
- )
- )
- for /l %%i in (1,1,%max%) do (
- set "res="
- for /l %%j in (1,1,%num%) do (
- set "var=!str%%j_%%i! "
- set "res=!res!!var:~0,5!"
- )
- echo !res!
- )
- pause
复制代码 【方法4】没想到批处理代码也不是很复杂,我把VBS的也贴上吧:- Const ForReading = 1
- Const ForWriting = 2
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- Set objFile = objFSO.OpenTextFile("In.txt",ForReading)
-
- Dim InputStr,lineIndex,TempArr,OutArr(100,100)
-
- Do Until objFile.AtEndOfStream
- InputStr = objFile.ReadLine
- TempArr = Split(InputStr," ")
- If UBound(TempArr) > MaxY Then MaxY = UBound(TempArr)
- For i = 0 To UBound(TempArr)
- OutArr(lineIndex,i) = TempArr(i)
- Next
- lineIndex = lineIndex + 1
- Loop
-
- objFile.Close
- Set objFile = objFSO.OpenTextFile("Out.txt",ForWriting,True)
- For i = 0 To MaxY
- For j = 0 To lineIndex - 1
- If OutArr(j,i) = "" Then OutArr(j,i) = " "
- OutStr = OutStr & OutArr(j,i) & " "
- Next
- objFile.WriteLine OutStr
- OutStr = ""
- Next
- objFile.Close
-
- Set objFile = Nothing
- Set objFSO = Nothing
复制代码 原文地址:http://www.cn-dos.net/forum/viewthread.php?tid=32931 |