Reputation: 385
My Text File has below content:
author : abc Revision : 123 Date : 9/4/2018 11.15.50 AM Path : testabc Message : Req ID:abcd1234 Rev:1.0.0 Status:something Notes:somethingabc Path : D:\temp
I want this content to look like this below:
author : abc Revision : 123 Date : 9/4/2018 11.15.50 AM Path : testabc Req ID:abcd1234 Rev:1.0.0 Status:something Notes:somethingabc Path : D:\temp
I need to delete the word "Message :" only (in the 5th line) and remove the spaces for the next three lines.
I have tried below:
$content = Get-Content "D:\test.txt"
$content | Foreach {$_.TrimStart('Message : ')} | Foreach {$_.TrimStart()} | Set-Content "D:\test.txt"
Upvotes: 1
Views: 2448
Reputation:
The IMO easiest way is the RegEx based -Replace
operator.
(Get-Content .\test.txt ) -replace "^(Message\s+:\s+|\s+)"
See the RegEx working here with an explanation
The RE anchors at line begin ^
and has an alternate it matches either
Message\s+:\s+
literal Message followed by at least one space a colon and at least one space
Or |
just spaces or more precise any whitespace character (equal to [\r\n\t\f\v ]
)
And replaces them with nothing ,""
which hasn't to be expressed but is implied.
Upvotes: 3
Reputation: 338208
You can use the -replace
operator, like this
$lines = Get-Content "D:\test.txt"
$lines -replace "Message : " -replace "^\s+" | Set-Content "D:\test.txt"
Notes:
-replace "A","B"
replaces A
with B
. If you omit B
, it effectively removes A
(i.e. replaces it with nothing).-replace
can be chained-replace
works with regular expressions, ^\s+
means "multiple spaces at the start of the line"ForEach
here - Get-Content
gives you an array of lines, -replace
runs for every line.Upvotes: 4