簡體   English   中英

Powershell:逐行讀取文本文件並在“ |”上分割

[英]Powershell: Read Text file line by line and split on “|”

我在使用“ |”將行拆分為數組時遇到麻煩 在文本文件中,並按一定順序重新組裝。 有多個行,如文本文件中的原始行。

這是原始行:

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 

編輯:對於基於-join和避免+=來構建數組的替代建議,向LotPings致謝(效率低下,因為它在每次迭代時都會重建數組):

$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"

由於您的輸入文件實際上是不帶標題的CSV文件,並且這些字段由豎線符號|分隔| ,為什么不這樣使用Import-Csv

$fileIn  = 'C:\Names\Complete\complete.txt'
$fileOut = 'C:\Names\Complete\index.txt'
(Import-Csv -Path $File -Delimiter '|' -Header 'Item','LastName','FirstName','AidYear','Type','FileName' | 
    ForEach-Object {
        "{0}|{1}|{2}|{3}|{4}|{5}" -f $_.Item, $_.Type, $_.LastName, $_.FirstName, $_.AidYear, $_.FileName
    }
) | Add-Content -Path $fileOut -Encoding Ascii

要提供更多PowerShell慣用的解決方案:

# Sample input line.
$line = '80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf'

# Split by '|', rearrange, then re-join with '|'
($line -split '\|')[0,4,1,2,3,5] -join '|'

請注意,PowerShell的索引語法(在[...]內部)如何足夠靈活以接受要提取的任意索引數組 (列表)。

另請注意-split的RHS操作數是\\| ,即逃脫的 | 焦炭,考慮到。 | 在那兒有特殊的含義(因為它被解釋為regex )。

放在一起:

$File = 'c:\Names\Complete\complete.txt'
Get-Content $File | ForEach-Object {
  ($_ -split '\|')[0,4,1,2,3,5] -join '|'
} | Out-File -LiteralPath C:\Names\Complete\index.txt -Encoding ascii

至於你嘗試什么

$Arr = $File -split '|'

首先,問題是-split操作應用於輸入文件路徑 ,而不是文件內容

其次,如上所述,用文字 | 字符, \\| 必須傳遞給-split ,因為它需要一個正則表達式 (正則表達式)。

而且,與其在-Append 的循環內使用Out-File-AppendForEach-Object使用單個管道更為有效,如上所示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM