Morten S.
Morten S.

Reputation: 41

Powershell: Replace text on specific line in file

I have some text files looking something like this:


Text 05-09-18
Text 17-09-18
Text 17-09-18

Text 24-09-18
Text 17-10-18


On line 15 in the .txt files, I'm trying to change from 24-09-18 to 24-09-2018.
Changing only this and not the other ones.

Here's what I'm been doing so far:

$infolder = Get-ChildItem C:\folder\*.txt -rec
foreach ($file in $infolder)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_[15] -replace '-18','-2018'} |
Set-Content $file}

Upvotes: 4

Views: 7057

Answers (3)

mahmoud elgml
mahmoud elgml

Reputation: 311

did some enhancement to "Morten S." answer

here you can replace all the line by putting the array index in first parameter of the -replace like this

$filecontent = Get-Content -Path C:\path\to\file.txt
$filecontent[15] = $filecontent[15] -replace $filecontent[15],'some text'
Set-Content -Path C:\path\to\file.txt -Value $filecontent

Upvotes: 1

Morten S.
Morten S.

Reputation: 41

Thank you for your help This works for me, it looks after files in C:\folder\
In each file, on line 14 it replaces -18 with -2018.
Saves all changes in the original file.

ForEach ($file in (Get-ChildItem -Path C:\Folder\))
{
$filecontent = Get-Content -path $file 
$filecontent[14] = $filecontent[14] -replace '-18','-2018' 
Set-Content $file.PSpath -Value $filecontent 
}

Upvotes: 0

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10764

Get-Content reads the contents of the file into an array, if used as the right side of an assignment statement. You can therefore do the following:

 $filecontent = Get-Content -Path C:\path\to\file.txt
 $filecontent[15] = $filecontent[15] -replace '-18','-2018'
 $Set-Content -Path C:\path\to\file.txt -Value $filecontent

You can find more detailed documentation on Microsoft's pages for Get-Content, -replace, and Set-Content.

Note: PowerShell arrays are zero origin. If you want to alter the sixteenth line, use the code above. If you want to alter the fifteenth line, use $filecontent[14] instead of $filecontent[15].

Upvotes: 6

Related Questions