4

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}
asked Sep 26, 2018 at 17:20
1

3 Answers 3

6

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].

answered Sep 26, 2018 at 17:39
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Jeff But this only works on a specific file right? Can it be modified to do the same to all files in a folder, named text1.txt, text2.txt etc...
You can wrap the code above in a ForEach ($file in (Get-ChildItem -Path ...)) {...}, and replace the explicit path in the code above with $file.
1

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
answered Dec 15, 2021 at 12:54

Comments

0

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 
}
answered Sep 28, 2018 at 14:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.