Powershell:逐行读取文本文件并在 "|"上拆分

标签 powershell csv text-parsing

我无法使用“|”将一行拆分为一个数组在文本文件中并按特定顺序重新组装它。与文本文件中的原始行一样,有多行。

这是原始行:

80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf

我需要它看起来像这样:
80055555|DCDOCS|Lastname|Firstname|AidYear|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf

这是我正在使用的代码:
$File = 'c:\Names\Complete\complete.txt'
$Arr = $File -split '|'
foreach ($line in Get-Content $File)
{
  $outputline = $Arr[0] + "|" + $Arr[4] + "|" + $Arr[1] + "|" + $Arr[2] + "|" + 
    "@@" + $Arr[5] |
      Out-File -filepath "C:\Names\Complete\index.txt" -Encoding "ascii" -append 
}

最佳答案

您需要自己处理文件的每一行,然后拆分它们。

$File = get-content "D:\test\1234.txt"
foreach ($line in $File){
    $Arr = $line.Split('|')
    [array]$OutputFile +=  $Arr[0] + "|" + $Arr[4] + "|" + $Arr[1] + "|" + $Arr[2] + "|" + "@@" + $Arr[5] 
}
$OutputFile | out-file -filepath "D:\test\4321.txt" -Encoding "ascii" -append 

编辑:感谢 LotPings 提供基于 -join 的替代建议以及避免+=构建数组(这是低效的,因为它在每次迭代时重建数组):
$File = get-content "D:\test\1234.txt"
$OutputFile = foreach($line in $File){($line.split('|'))[0,4,1,2,3,5] -Join '|'}
$OutputFile | out-file -filepath "D:\test\4321.txt" -Encoding "ascii"

关于Powershell:逐行读取文本文件并在 "|"上拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764858/

相关文章:

linux - 在一个文件的行中搜索另一个文件中的部分匹配项(Mac/Linux/Unix 命令行)

python - 如何在Python串行解析器中确定句子的结尾?

html - ConvertTo-Html cmdlet 如何将列添加到输出

powershell - 如何使用 Powershell 查询 msSFU30MaxUidNumber 属性?

Node.js 中的 Json 到 csv

sql - 去除单词中的空格

math - 计算一串简单的数学表达式

powershell - 从批处理文件运行时,Powershell 中的 Get-Filehash SHA256 加密会删除最后 4 位数字

powershell - IT 任务 : F# script vs Powershell script

c - 在c中读取巨大的CSV文件