问题描述
任务应该很简单,但我不知道如何完成它。
假设我有一个由以下单列数据组成的 CSV 文件(实际上有数百行,而不仅仅是六行)。
AAAAA BBBBB CCCCC ddddD EEEEE FFFFF
使用 Powershell,我想根据上述文件自动创建一个新的 CSV 文件,该文件将数据拆分为以下两个制表符分隔的列。
AAAAA BBBBB CCCCC ddddD EEEEE FFFFF
我怎样才能做到这一点?谢谢
解决方法
您使用了 batch-file
标签,所以我必须假设批处理文件解决方案是可以的。
阅读一行,记住它,并且只在循环的每一秒运行一次:
@echo off
setlocal enabledelayedexpansion
set "first="
for /f "delims=" %%a in (w.csv) do (
if not defined first (
set "first=%%a"
) else (
echo !first! %%a
set "first="
)
)
if defined first echo %first% -----
最后一行处理奇数行数。
,您为第一个文件显示的不是 CSV 文件,只是一个文本文件,每个值都在一个新行上。 您显然想要的结果是一个没有标题的制表符分隔文件。
在 PowerShell 中,我认为最简单的方法是使用这样的索引循环:
$fileA = Get-Content -Path 'Path\To\The\File' # read the values as string array
$result = for ($i = 0; $i -lt $fileA.Count; $i += 2) { # loop through the lines in steps of 2
"{0}`t{1}" -f $fileA[$i],$fileA[$i + 1] # output the values delimited with a TAB character
}
# show in console window
$result
# write to file
$result | Set-Content -Path 'Path\To\The\New\File'
输出:
AAAAA BBBBB
CCCCC DDDDD
EEEEE FFFFF
如果您想创建带有标题的真实 CSV 文件,请输出对象而不是字符串:
$fileA = Get-Content -Path 'Path\To\The\File' # read the values as string array
$result = for ($i = 0; $i -lt $fileA.Count; $i += 2) { # loop through the lines in steps of 2
# output an object with column headers
[PsCustomObject]@{ ColumnA = $fileA[$i]; ColumnB = $fileA[$i + 1] }
}
# show in console window
$result
# write to file
$result | Export-Csv -Path 'Path\To\The\New\File' -Delimiter "`t" -NoTypeInformation
输出:
ColumnA ColumnB
------- -------
AAAAA BBBBB
CCCCC DDDDD
EEEEE FFFFF
,
接下来是批处理文件解决方案,它的处理方式略有不同。
本质上,如果是奇数行号,则输出内容后跟水平制表符,如果是偶数,则输出行内容后跟回车和换行符。它还被编写为在输出以 ;
字符开头或包含 !
字符的内容时不会出现问题。
在测试前,请仅将行 4
和 5
上的源文件和目标文件调整为您自己的绝对或相对文件名:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F "Delims==" %%G In ('"(Set {) 2>NUL"') Do Set "%%G="
Set "{s}=C:\Users\Robith\Documents\input.csv"
Set "{d}=C:\Users\Robith\Desktop\output.csv"
If Not Exist "%{s}%" GoTo :EOF
For /F %%G In ('Copy /Z "%~f0" NUL') Do Set "{r}=%%G"
For /F "Delims==" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe OS Call /?
^| %SystemRoot%\System32\find.exe "=="') Do Set "{t}=%%G"
(Set {n}=^
% 0x0A %
)
( For /F Delims^=^ EOL^= %%G In ('Type "%{s}%"
^| %SystemRoot%\System32\find.exe /V ""') Do (
Set /A {i} += 1,{m} = {i} %% 2
Set "{l}=%%G"
SetLocal EnableDelayedExpansion
If !{m}! Equ 1 (Set /P "=!{l}!%{t}:~-1%"<NUL
) Else Set /P "=!{l}!%{r}%!{n}!"<NUL
EndLocal)) 1>"%{d}%"
For /F "Delims==" %%G In ('"(Set {) 2>NUL"') Do Set "%%G="