【问题标题】:Get content from 2 files and insert into 1 file从 2 个文件中获取内容并插入到 1 个文件中
【发布时间】:2017-06-13 08:50:29
【问题描述】:

大家好,

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

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

示例:

导入文件1.txt

导入文件2.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

【问题讨论】:

  • 一个简单的复制命令应该可以工作copy "test1.txt" + "test2.txt" "final.txt"
  • @RanadipDutta 这是一个 cmd,exe 答案是一个接一个地附加文件,而不是并排。

标签: powershell powershell-cmdlet


【解决方案1】:

您可以使用数组来使用以下内容:

$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

【讨论】:

  • 非常感谢,我还有一个问题。 0.. 做什么?为什么文字相距甚远?我只需要一个空间。你帮了我很多谢谢:)
  • 我将解释添加到我的答案中。
【解决方案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

【讨论】:

    【解决方案3】:

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

    $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
    

    【讨论】:

      【解决方案4】:

      其他解决方案

      $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
      

      【讨论】:

        猜你喜欢
        • 2017-04-03
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2017-10-11
        • 2015-01-01
        • 1970-01-01
        • 2019-09-08
        • 2013-06-19
        相关资源
        最近更新 更多