Writing Nautilus Scripts

On 2016/08/02 at 13:38

I was trying to add a menu item to Nautilus context menu for easily converting encoding of a subtitle files. Because some default encodings of downloaded subtitles can not be accepted by the VLC player. I found there is a cool feature of Nautilus called nautilus script. Users can simply write and save a script into /.local/share/nautilus/scripts and the script can be executed by simply clicking a menu item in Nautilus context menu.

There are 4 environment variables Nautilus will set for ths cripts to get the information of current files/directories.

Therefore, I simply wrote a ruby script to convert the encoding of selected files from simplified chinese/utf16 to traditional chinese/utf8 as following:

#!/usr/bin/env ruby

#log = open('ruby.log', 'w')

paths.split("\n").each do |path|
#   log.print path + "\n"
    tmpPath = path + ".tmp"
    newPath = path.dup
    newPath[newPath.rindex(".")..0] = ".new"
    %x[ iconv -f utf16 -t gb2312//TRANSLIT '#{path}' | 
        iconv -f gb2312 -t big5//TRANSLIT | 
        iconv -f big5 -t utf8//TRANSLIT > '#{tmpPath}' ]
    %x[ tr -d '\r' < '#{tmpPath}' > '#{newPath}' ]  # converting CRLF to LF
    %x[ rm '#{tmpPath}' ]

Finally, I can easily execute the nautilus script by clicking the menu item in the context menu.

script in context menu