Skip to content

Instantly share code, notes, and snippets.

@sean-m
Created December 31, 2024 01:55
Show Gist options
  • Save sean-m/fb04bced265ba1f5e29f6ea9fa3ae1a9 to your computer and use it in GitHub Desktop.
Save sean-m/fb04bced265ba1f5e29f6ea9fa3ae1a9 to your computer and use it in GitHub Desktop.
Apply a timeshift to an srt file and write to stdout.
#!/usr/bin/env pwsh
param($srtFile, $shiftMiliseconds=0)
if (-not $srtFile) {
throw "Must set srtFile path."
return
}
$srtLines = Get-Content $srtFile
class Element {
[int]$index
[string]$span
[string[]]$body = @()
[string]ToString() {
$sb = [System.Text.StringBuilder]::new()
$sb.AppendLine($this.index.ToString()) | out-null
$sb.AppendLine($this.span)
$this.body | foreach { $sb.AppendLine($_) }
$sb.AppendLine()
return $sb.ToString()
}
}
$elements = [System.Collections.Generic.List[object]]::new()
$element = $null
foreach ($l in $srtLines) {
if ([string]::IsNullOrEmpty($l.Trim())) {
if ($element) {
$elements.Add($element)
$element = $null
continue
}
}
if (-not $element) {
$element = [Element]::new()
}
if ($l -match '^[0-9]+\s*$') {
$element.index = [int]($Matches[0])
}
elseif ($l -match '^(?<first>[0]{2}:[0-9]{2}:)(?<firstSeconds>[0-9]{2},[0-9]{3}) --> (?<second>[0]{2}:[0-9]{2}:)(?<secondSeconds>[0-9]{2},[0-9]{3})$') {
$firstSeconds = [int]$matches.firstSeconds.Replace(',','')
$secondSeconds = [int]$matches.secondSeconds.Replace(',','')
if ($shiftMiliseconds -ne 0) {
$firstSeconds = $firstSeconds += $shiftMiliseconds
$secondSeconds = $secondSeconds += $shiftMiliseconds
$element.span = $Matches.first + $firstSeconds.ToString("N").Replace('.000','') + " --> " + $Matches.second + $secondSeconds.ToString("N").Replace('.000','')
}
else {
$element.span = $Matches[0]
}
} elseif ($l) {
$element.body += $l
}
}
$elements | foreach { $_.ToString() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment