从一个txt文件中复制行,并使用PowerShell将其替换到另一个特定编号行的txt文件中



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

我有第一步复制特定的编号行,需要第二步粘贴在特定的编号线:

Get-Content C:TempMegateoHash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:TempMegateoMonin.txt

查看问题的标题以及您撰写的最新评论,您实际上是在寻找替换一行的方法,而不是插入新行。

尝试

在现实生活中,你想从文件中获得输入:

# Get your replacement line from the first file
$replacementText = Get-Content -Path 'C:TempMegateoHash.txt' -TotalCount 121 | Select-Object -Skip 1 -First 1
# and read the file you want to update
$lines = Get-Content -Path 'C:TempMegateoMonin.txt'

但对于这里的演示,我使用的是:

$replacementText = "This is the new line"
$lines = @"
text text text text text text
text text text text text text
Replace this line with something NEW
text text text text text text
text text text text text text
"@ -split 'r?n'

如果你已经知道要替换的行索引,只需进行

$index = 2
if ($index -lt $lines.Count) {
$lines[$index] = $replacementText
# and write the updated file
$lines | Set-Content -Path 'C:TempMegateoMonin.txt'
}
else {
Write-Warning "'$index' exceeds the total number of lines ($($lines.Count))"
}

但是,如果您需要首先使用搜索字符串查找索引,您可以在$lines数组上使用.IndexOf()方法,如Santiago的有用答案(区分大小写(所示,也可以使用下面的.FindIndex()不区分大小写地查找行
请记住,如果找不到要查找的字符串,.IndexOf().FindIndex()都可以返回值-1。

# make the FindIndex() array method look for the string case-insensitively
$predicate = [Predicate[String]]{param($s) $s -like 'replace this line*'}
# try and find the index of the line to replace. if not found, this returns -1
$index = [array]::FindIndex([string[]]$lines, $predicate)
if ($index -ge 0) {
# now change the line at position $index with the replacement string
$lines[$index] = $replacementText
# and write the updated file
$lines | Set-Content -Path 'C:TempMegateoMonin.txt'
}
else {
Write-Warning "Could not find the requested line"
}

您需要提供更多关于从另一个文件插入行的位置(索引(的详细信息,但要向您展示一种解决内容文件索引切片问题的方法。假设我们有test.txt,它看起来像这样:

text text text text text text
text text text text text text
insert line below here
text text text text text text
text text text text text text

我们想在insert line below here下面插入hello world!,下面是如何做到的:

$toInsert = 'hello world!'
$content = Get-Content ./test.txt
$index = $content.IndexOf('insert line below here')
$newContent = @(
$content[0..$index++]
$toInsert
$content[$index..($content.Count - 1)]
)
$newContent | Out-File path/to/newfile....

现在,如果我们检查$newContent:

PS /> $newContent
text text text text text text
text text text text text text
insert line below here
hello world!
text text text text text text
text text text text text text

最新更新