I have never worked with powershell before, and Google didn't give me answers for exactly what I need. I hope you guys can help me. I need to find all the files in the directory(including sub-directories) that have 2 lines:
aaa aaa
bbb bbb
and replace the second line with ccc
Replacement shouldn't happen if line bbb bbb doesn't follow right after aaa aaa.
Here's what I have so far:
$line3 = "aaa[ ]*aaa[ ]*bbb[ ]*bbb"
Get-ChildItem -exclude *.bak -recurse *.txt | Where-Object {$_.Attributes -ne "Directory"} |
ForEach-Object {
Copy-Item $_ "$($_).bak";
$wholeFile = [IO.File]::ReadAllText("$_");
$wholeFile = $wholeFile.replace("`n", " ");
$wholeFile = $wholeFile.replace("`r", " ");
$temp3 = $wholeFile | Select-String -pattern $line3 -quiet;
if(($temp3 -eq "True")){
(Get-Content $_) -replace "bbb[ ]*bbb", "ccc" | Set-Content -path $_;
}
else{
echo failed
}
}
I think this code almost work except if a file has 2 occurrences of "bbb bbb": one that follows right after "aaa aaa" and another one without "aaa aaa". both lines would get replaced, and I need only the first one to be replaced.Is there any way to fix it? Can someone with more experience tell me if I missed something? Is there any simpler/shorter solutions for what I need? I've seen so many neat one-line solutions in powershell. Is there anything like that for my case? Thanks