合并多语言字幕脚本

很久之前写过怎么把多个字幕合并在在一起,也就是中英双语啦,用mplayer载入,试过cat来暴力合并,即把第二个字幕直接附加到第一个字幕的底部

cat chs.srt eng.srt > chs-eng.srt

可惜显示不正常,所以才用diff法来合并。其实用cat方法是可行了,mplayer命令加上参数”-overlapsub“就行了(之前是用“overlapsub=1”才出错了)。

合并多行

这样直接合并后会出现对白过多,如中文这条时间轴有3行对白,英文也3行,就6行了,这样看很不爽,也不方便对照,所以要分别对每个语言合并到一行,就是中文一行,英文一行,之前我是Vim来搞定的。不过实在麻烦而很没效率,昨晚研究了整晚,先用while、read、grep、echo反复来读取处理行, 处理速度非常慢。

最后憋的一条命令,真的是一条awk命令,合并字幕瞬间完成,把要处理的字幕,然后把结果重定向到新文件即可,

awk '{if ($0 ~ "^[1-9][0-9]*$|-->") {print $0} else {if ($0 ~ "^$") {print "\n"} else {printf("%s ",$0)}}}'

编码换行问题

其实上边那条命令可能会无效的,因为下载来的字幕,比如从射手网,编码多数是gb2312,换行也是DOS方式(用Vim打开会看到行尾都有“^M”),我就被这两个问题郁闷了很久。

  • 在终端下cat字幕输出中文是乱码(因为终端是用uft-8),而数字和英文则能正常显示,解决方法就是不要理会。
  • 换行问题如果处理的话,上面awk命令处理起来就无效了,因为再加个验证换行的表达式真实麻烦,不过可以先用dos2unix转换。

一步到位命令

综合上面的问题,一步到位命令就是

cat $* | fromdos | awk '{if ($0 ~ "^[1-9][0-9]*$|-->") {print $0} else {if ($0 ~ "^$") {print "\n"} else {printf("%s ",$0)}}}' > chs-eng.srt

先用cat合并字幕,然后管道输出到dos2unix转换换行,然后又再管道到awk合并多行,最后又是管道输出结果到文件,至于编码不用管了,可以在mplayer加参数“-subcp cp936”设定(前端都有这个选项设置的)。

脚本

这么长的命令当然不可能每次用都打一遍,设置alias引号转义又麻烦,所以还是写成脚本,扔进“/usr/bin”里

#!/bin/bash
# Name: mrgsub
# Description: Merge mulit subtitles, each subtitle to one line
# Usage: mrgsub sub1.srt sub2.srt > sub.srt
# Example: mrgsub chs.srt eng.srt > chs-eng.srt
# mplayer -overlapsub -sub chs-eng.srt
cat $* | fromdos | awk '{if ($0 ~ "^[1-9][0-9]*$|-->") {print $0} else {if ($0 ~ "^$") {print "\n"} else {printf("%s ",$0)}}}'

“$*”也就是脚本的参数传递给cat命令。以后只需要用

mrgsub chs.srt eng.srt > chs-eng.srt
mplayer -overlapsub -sub chs-eng.srt

即可搞定,几乎是瞬间完成。

This entry was posted in 经验技巧 and tagged , . Bookmark the permalink.

2 Responses to 合并多语言字幕脚本

  1. Chester says:

    命令中有几个中文符号,修改后是
    cat $* | dos2unix | awk ‘{if ($0 ~ “^[1-9][0-9]*$|->”) {print $0} else {if ($0 ~ “^$”) {print “\n”} else {printf(“%s “,$0)}}}’

    回复回复
  2. muzuiget says:

    @Chester
    嗯,WP自动转换的,很恼人。

    回复回复

发表评论

您的电子邮箱不会被公开。 标记为 * 的区域必须填写

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">