PowerShell Text File Edit

Omar Hegazy 41 Reputation points
2020-12-17T18:52:50.323+00:00

Hello,

I have a subtitle file. The below is a sample of it which is a repetitve pattern but with different time and phrases. (note: it has 3 languages together each in a line).

112
00:06:53,04 --> 00:06:55,13
so afterwards I started reading books,
Tak jsem pak začala číst,
فبدأت أقرأ في كل الكتب

113
00:06:55,17 --> 00:06:57,04
all the books or most of them,
všechny knihy nebo většinu,
أو معظمها

Now i want to have 3 different files each has 1 language only. So, i want a code that will delete 2 lines of the selected languages, and leave me with single language i select.

Windows for business Windows Server User experience PowerShell
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2020-12-18T03:28:26.437+00:00

    Try this:

    $FileName = $null,"c:\junk\Lang1.txt","c:\junk\Lang2.txt","c:\junk\Lang3.txt"  # $null is there so the inner loop's $_ can be used without subtracting 1
    # Remove any old files
    1..3 |
        ForEach-Object{
            Remove-Item $FileName[$_] -ErrorAction SilentlyContinue
        }
    
    Get-ChildItem c:\junk\l.txt |
        Select-String -Pattern "^\d\d\d$" -Context 0,4 |
            ForEach-Object{
                $x = $_
                1..3 | ForEach-Object{ 
                    $x.Line | Out-File $FileName[$_] -Append
                    $x.Context.PostContext[0] | Out-File $FileName[$_] -Append  # timestamp?
                    $x.Context.PostContext[$_] |Out-File $FileName[$_] -Append  # text
                    "" |Out-File $FileName[$_] -Append                          # blank line
                }
            }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.