如何在powershell中更改列位置?

时间:2015-02-11 00:17:50

标签: powershell position

有没有简单的方法来改变列位置?我正在寻找一种方法如何将列1从开始移动到每行和每行,并且我想添加零列作为第二列的第二列。请参阅下面的txt文件示例 感谢您的任何建议。

档案样本

TEXT1,02/10/2015,55.930,57.005,55.600,56.890,1890  
TEXT2,02/10/2015,51.060,52.620,50.850,52.510,4935
TEXT3,02/10/2015,50.014,50.74,55.55,52.55,5551

输出:

02/10/2015,55.930,57.005,55.600,56.890,1890,0,TEXT1  
02/10/2015,51.060,52.620,50.850,52.510,4935,0,TEXT2
02/10/2015,50.014,50.74,55.55,52.55,5551,0,TEXT3

3 个答案:

答案 0 :(得分:1)

当然,用逗号分割,吐出结果减去第一个用逗号连接的结果,添加一个0,然后将第一个结果添加到结尾并用逗号连接整个结果。类似的东西:

$Input = @"
TEXT1,02/10/2015,55.930,57.005,55.600,56.890,1890
TEXT2,02/10/2015,51.060,52.620,50.850,52.510,4935
TEXT3,02/10/2015,50.014,50.74,55.55,52.55,5551
"@ -split "`n"|ForEach{$_.trim()}

$Input|ForEach{
    $split = $_.split(',')
    ($Split[1..($split.count-1)]-join ','),0,$split[0] -join ','
}

答案 1 :(得分:1)

我创建了文件test.txt来包含您的示例数据。我为每个字段分配了一个名称,"一个","两个",#34;三个"等我可以按名称选择它们,然后选择并按照你想要的顺序导出回csv。

首先,将零添加到最后,它将最后结束。

gc .\test.txt  | %{ "$_,0" } | Out-File test1.txt

然后,重新排列顺序。

Import-Csv .\test.txt -Header "one","two","three","four","five","six","seven","eight" | Select-Object -Property two,three,four,five,six,seven,eight,one | Export-Csv test2.txt -NoTypeInformation

这将取输出文件并删除引号和标题行,如果你不想拥有它们。

gc .\test2.txt | %{ $_.replace('"','')} | Select-Object -Skip 1 | out-file test3.txt

答案 2 :(得分:1)

另一种选择:

#Prepare test file
(@'
TEXT1,02/10/2015,55.930,57.005,55.600,56.890,1890  
TEXT2,02/10/2015,51.060,52.620,50.850,52.510,4935
TEXT3,02/10/2015,50.014,50.74,55.55,52.55,5551
'@).split("`n") |
foreach {$_.trim()} | 
sc testfile.txt

#Script starts here
$file = 'testfile.txt'

(get-content $file -ReadCount 0) |
foreach  {
'{1},{2},{3},{4},{5},{6},0,{0}' -f $_.split(',')
} | Set-Content $file

#End of script

#show results    
get-content $file

02/10/2015,55.930,57.005,55.600,56.890,1890,0,TEXT1
02/10/2015,51.060,52.620,50.850,52.510,4935,0,TEXT2
02/10/2015,50.014,50.74,55.55,52.55,5551,0,TEXT3