Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, June 3, 2014 4:13 AM
How do i edit the text (or paragraphs) in text files using PowerShell?
Thak You
All replies (4)
Tuesday, June 3, 2014 4:36 AM ✅Answered | 2 votes
Hi,
That's a pretty broad question, do you have something specific you're trying to accomplish?
As one example though, this will create an input file (you could just use one you already have, but this is a fully contained example), read it, replace the word 'text' with the word 'fun', and write an output file:
$exampleFile = @"
This is some text.
This is some more text.
This is even more text.
"@
$exampleFile | Out-File .\input.txt
(Get-Content .\input.txt ).Replace('text','fun') | Out-File .\output.txt
Don't retire TechNet! - (Don't give up yet - 12,950+ strong and growing)
Tuesday, June 3, 2014 8:45 AM ✅Answered | 2 votes
Hi Oju,
Mike's example shows you how to manipulate file content (in the final line. Everything above that is just boilerplate to create a text file, not work with it). I'll simply expand on it by providing a link that is a good introduction to working with strings.
Because what you get when you use "Get-Content" on a txt file is a list of strings, so you can use those tools on 'em.
Cheers and good luck learning Powershell,
Fred
There's no place like 127.0.0.1
Thursday, June 5, 2014 6:33 AM ✅Answered | 1 vote
Hi Oju,
you can do a lot of things with string, replace is just one of the more common operations. Here's the full list of functions string has:
Furthermore, you can build text line by line and then save it to a file, using Out-File or Set-Content.
A short example:
# Example
$strings = @()
$strings += "I'm the first line!"
$strings += "I'm the second line!"
$strings += @"
I'm line three!
I'm line four!
"@
$strings | Set-Content "C:\temp\test.txt"
Cheers,
Fred
There's no place like 127.0.0.1
Thursday, June 5, 2014 6:00 AM
So that means I can only replace texts, not work like we do in word?
Reason I asked the Question.
I am Learning Python. I create .py files using Notepad++, I was wondering if i could edit the lines in the .py file (Example: Print "Text Text Text", etc.) using powershell, as we can create .py files using New-Item Command.