powershell 如何替换特定行号

chhkpiq4  于 2023-01-17  发布在  Shell
关注(0)|答案(4)|浏览(138)

我正在尝试使用PowerShell替换txt文件中的第11行。
首先,我试着替换一个特定的词,但它改变了太多:

$output= (Resolve-DnsName -name name1).IPAddress 

(Get-Content "C:\test\test.txt") -replace "IPADDRESS=","IPADDRESS=$output"  | Set-Content C:\test\test.txt
5anewei6

5anewei61#

如果要替换某行中的某些内容,可以对Get-Content cmdlet返回的字符串 array 使用索引运算符:

$content = Get-Content "C:\test\test.txt"
$content[10] = -replace "IPADDRESS=","IPADDRESS=$output" 
$content | Set-Content C:\test\test.txt
aoyhnmkz

aoyhnmkz2#

如果有人发现上面的答案对他们不起作用,那么这个答案就起作用了:

$content = Get-Content "C:\test\test.txt"
$contentUpdate = $content[10] -replace "IPADDRESS=","IPADDRESS=$output" 
Set-Content C:\test\test.txt $contentUpdate
cedebl8k

cedebl8k3#

$content = Get-Content "$file"
$content[$line - 1] = ($content[$line - 1] -replace "IPADDRESS=","IPADDRESS=$output")
Set-Content "$file" $content

这个对我很管用。

pengsaosao

pengsaosao4#

PowerShell 7+
$output="127.0.0.1"
$content = Get-Content "C:\test\test.txt"
$content[10] =$content[10] -replace "IPADDRESS=","IPADDRESS=$output"
$content| Out-File "C:\test\test.txt"

相关问题