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.
- The [15] overrides the .txt file with a empty one.
- If [15] is not present then it changes all dates in the .txt file.
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}
-
Possible duplicate of How to replace of a specific line numberuser6811411– user68114112018年09月27日 13:22:25 +00:00Commented Sep 27, 2018 at 13:22
3 Answers 3
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].
2 Comments
ForEach ($file in (Get-ChildItem -Path ...)) {...}, and replace the explicit path in the code above with $file.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
Comments
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
}