'How to replace of a specific line number
I'm trying to replace line number 11 in a txt file using PowerShell.
Firstly I tried replacing a specific word, but it changed too much:
$output= (Resolve-DnsName -name name1).IPAddress
(Get-Content "C:\test\test.txt") -replace "IPADDRESS=","IPADDRESS=$output" | Set-Content C:\test\test.txt
Solution 1:[1]
For anyone finding that the above answer doesn't work for them, this works:
$content = Get-Content "C:\test\test.txt"
$contentUpdate = $content[10] -replace "IPADDRESS=","IPADDRESS=$output"
Set-Content C:\test\test.txt $contentUpdate
Solution 2:[2]
$content = Get-Content "$file"
$content[$line - 1] = ($content[$line - 1] -replace "IPADDRESS=","IPADDRESS=$output")
Set-Content "$file" $content
This one worked for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | takeoff127 |
| Solution 2 | ouflak |
