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

Get content from 2 files and insert into 1 file

大家好,

我正在尝试将 2 个文件中的内容插入到 2 个新列中 final.txt

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

示例:

进口file1.txt

导入file2.txt

出口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

您可以使用以下数组:

$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

JPBlanc 解决方案的一个变体,但是

  • 创建文件名为 headers
  • 的 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

合并版本,因为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

其他解决方案

$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