【发布时间】:2015-05-17 18:59:36
【问题描述】:
我正在尝试格式化 0 到 3 列之间的大型文本文件(~300MB):
12345|123 Main St, New York|91110
23456|234 Main St, New York
34567|345 Main St, New York|91110
输出应该是:
000000000012345,"123 Main St, New York",91110,,,,,,,,,,,,
000000000023456,"234 Main St, New York",,,,,,,,,,,,,
000000000034567,"345 Main St, New York",91110,,,,,,,,,,,,
我是 powershell 的新手,但我读过我应该避免使用 Get-Content,所以我使用的是 StreamReader。还是太慢了:
function append-comma{} #helper function to append the correct amount of commas to each line
$separator = '|'
$infile = "\large_data.csv"
$outfile = "new_file.csv"
$target_file_in = New-Object System.IO.StreamReader -Arg $infile
If ($header -eq 'TRUE') {
$firstline = $target_file_in.ReadLine() #skip header if exists
}
while (!$target_file_in.EndOfStream ) {
$line = $target_file_in.ReadLine()
$a = $line.split($separator)[0].trim()
$b = ""
$c = ""
if ($dataType -eq 'ECN'){$a = $a.padleft(15,'0')}
if ($line.split($separator)[1].length -gt 0){$b = $line.split($separator)[1].trim()}
if ($line.split($separator)[2].length -gt 0){$c = $line.split($separator)[2].trim()}
$line = $a +',"'+$b+'","'+$c +'"'
$line -replace '(?m)"([^,]*?)"(?=,|$)', '$1' |append-comma >> $outfile
}
$target_file_in.close()
我正在为团队中的其他人构建它,并希望使用本指南添加一个 gui: http://blogs.technet.com/b/heyscriptingguy/archive/2014/08/01/i-39-ve-got-a-powershell-secret-adding-a-gui-to-scripts.aspx
在 Powershell 中是否有更快的方法来执行此操作? 我使用 Linux bash(Windows 上的 Cygwin64)编写了一个脚本,并在 Python 中编写了一个单独的脚本。两者都运行得更快,但我正在尝试编写一些可以在 Windows 平台上“批准”的脚本。
【问题讨论】:
-
第一个字段中的数字总是有 5 位数字吗?此外,是否需要修剪(即是否存在具有前导/尾随空格的字段的可能性)?
-
第一个字段可以是 1-15 个字符,但在 leftpad 之后总共应该是 15 个字符。修剪是必要的。
标签: shell powershell