从2个文件中获取内容并插入1个文件

时间:2017-06-13 08:50:30

标签: powershell cmdlet

大家好,

我尝试将2个文件中的内容插入2列new final.txt

他们在每个文件中只有一列

示例:

导入file1.txt

导入file2.txt

export final.txt

$file1 = Get-Content .\test1.txt
$file2 = Get-Content .\test2.txt
foreach ($i in $file1){
   foreach($y in $file2){
      Write-Host "$i" +  Write-Host "$y"
   }
}
Out-File .\final.txt

4 个答案:

答案 0 :(得分:2)

您可以使用以下数组:

$file1 = Get-Content .\test1.txt
$file2 = Get-Content .\test2.txt
0..$($file1.Length-1) | % {add-Content -Value "$($file1[$_]), $($file2[$_])" -Path final.txt} 

在表达式a..b中,..是范围运算符,它提供从ab的整数集合,请参阅about_operators

答案 1 :(得分:2)

JPBlanc解决方案的变体,但

  • 使用文件名作为标题创建csv
  • 迭代更多行
  • 双引号列并使用,作为分隔符
$file1 = Get-Content .\test1.txt
$file2 = Get-Content .\test2.txt
$Final = '.\final.csv'
$MaxLines = ([math]::max($file1.Length,$file2.Length)-1)
Set-Content -Value "`"test1.txt`",`"test2.txt`"" -Path $Final
0..$MaxLines| 
  ForEach {add-Content -Value "`"$($file1[$_])`",`"$($file2[$_])`"" -Path $Final}

示例输出:

> cat .\final.csv
"test1.txt","test2.txt"
"one","two"
"three","four"
"","six"
> import-csv .\final.csv

test1.txt test2.txt
--------- ---------
one       two
three     four
          six

答案 2 :(得分:0)

合并版本,因为Lotpings有权使用max nb line

$file1 = Get-Content C:\temp\test1.txt
$file2 = Get-Content C:\temp\test2.txt
$MaxNbLines = ([math]::max($file1.Length,$file2.Length)-1)

0..$MaxNbLines | %{[pscustomobject]@{file1=$file1[$_];file2=$file2[$_]}} | export-csv "C:\temp\resul.csv" -NoType

答案 3 :(得分:0)

其他解决方案

$file1="C:\temp\test1.txt"
$file2="C:\temp\test2.txt"
$Result="C:\temp\result.csv"

Select-String $file1, $file2 -pattern  "\b" | group LineNumber | 
    %{[pscustomobject]@{file1=$_.Group[0].Line;file2=$_.Group[1].Line}} | Export-Csv $Result -notype