![](/img/trans.png)
[英]PowerShell read text file line by line and find missing file in folders
[英]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
, -Append
在ForEach-Object
使用单个管道更为有效,如上所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.