如何使用 PowerShell 从 txt 列表中复制行并将其粘贴到另一个 txt 中的特定行?

如何使用 PowerShell 从 txt 列表中复制行并将其粘贴到另一个 txt 中的特定行?

我对 PowerShell 还比较陌生。我希望能够从列表文件中复制一行文本并将其粘贴到另一个文本文件的特定行上。

我已经完成第一步,需要帮助完成下一步的说明:

Get-Content C:\Temp\Megateo\Hash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:\Temp\Megateo\Monin.txt

答案1

这是完成这项工作的一种方法。因为你想代替目标行,除了标准数组之外不需要任何其他东西。无需插入,只需替换。[咧嘴笑]

代码 ...

$FirstFile = "$env:TEMP\FirstFile.txt"
$SecondFile = "$env:TEMP\SecondFile.txt"
$ThirdFile = "$env:TEMP\ThirdFile.txt"

#region "make files to work with"
# remove this entire "#region/#endregion" block when you are ready to work with your real data

# make a "first file" to work with
1..66 |
    ForEach-Object {
        '{0} is the 1st file line number' -f $_
        } |
    Set-Content -LiteralPath $FirstFile -Force

# make a "second file" to work with
1..66 |
    ForEach-Object {
        '--- {0} is the 2nd file line number ---' -f $_
        } |
    Set-Content -LiteralPath $SecondFile -Force
#endregion "make files to work with"

$1stFileSourceLine = 33
$2ndFileDestLine = 11
#$2ndFileDestLine = 17
#$2ndFileDestLine = 22

# the "-1" is because collections start at zero
$LineFromFirstFile = (Get-Content -LiteralPath $FirstFile)[$1stFileSourceLine - 1]
$SecondFile_Content = Get-Content -LiteralPath $SecondFile

$SecondFile_Content[$2ndFileDestLine - 1] = $LineFromFirstFile

Set-Content -LiteralPath $ThirdFile -Value $SecondFile_Content -Force

截断的内容$ThirdFile...

[*...snip...*] 

--- 6 is the 2nd file line number ---
--- 7 is the 2nd file line number ---
--- 8 is the 2nd file line number ---
--- 9 is the 2nd file line number ---
--- 10 is the 2nd file line number ---
33 is the 1st file line number
--- 12 is the 2nd file line number ---
--- 13 is the 2nd file line number ---
--- 14 is the 2nd file line number ---
--- 15 is the 2nd file line number ---
--- 16 is the 2nd file line number ---

[*...snip...*] 

代码的作用是什么……

  • 设置文件位置和名称

  • 创建用标记包裹的第 1 和第 2 个文件#region/#endregion。确认代码按预期工作后,只需将其删除。
  • 设置要复制的源文件行
  • 设置目标文件行来替换
    两个注释掉的行,它们是替代值,以确保它正在做我认为它正在做的事情。[咧嘴笑]
  • 读取第一个文件并抓取源文件行,
    正如注释指出的那样,索引号相差一 - 并且代码通过减去 1 来纠正它。
  • 读入第二个文件
  • 用第一个文件中的源行替换第二个文件的目标行
  • 将修改后的文件内容发送到,$ThirdFile
    覆盖其中一个工作文件通常不是一个好主意。所以我将修改后的内容发送到了第三个文件。

相关内容