使用 Powershell 交替拆分 CSV 列

Alternate-split CSV Column Using Powershell

任务应该很简单,但我不知道如何完成。

假设我有一个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 文件,只是一个文本文件,每个值都在一个新行上。 您显然想要的结果是一个没有 headers.

的制表符分隔文件

在 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

如果你想用 headers 创建一个 真正的 CSV 文件,输出 objects 而不是字符串:

$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 

下面是一个批处理文件解决方案,其处理方式略有不同。

本质上,如果是奇数行,则输出内容后跟水平制表符,如果是偶数,则输出行内容后跟回车return和换行。它还被编写为在输出以 ; 字符开头或包含 ! 字符的内容时不会出现问题。

请在测试前仅将第 45 行的源文件和目标文件调整为您自己的绝对或相对文件名:

@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="