Created
June 30, 2024 21:10
-
-
Save 12joan/a9b92a45b0be219acf6d7d737888872b to your computer and use it in GitHub Desktop.
A Ruby script that uses the `file` command to add or change file extensions for a list of files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'fileutils' | |
Entry = Struct.new(:path, :extension) do | |
def self.parse line | |
columns = line.chomp.split(/:\s*/) | |
return nil unless columns.length == 2 | |
path, extensions = columns | |
return nil if extensions == '???' | |
extension = extensions.split('/').first | |
new(path, extension) | |
end | |
def path_without_extension | |
path.split('.').first | |
end | |
def move | |
new_path = path_without_extension + '.' + extension | |
FileUtils.mv(path, new_path) unless path == new_path | |
end | |
end | |
entries = `file --extension #{ARGV.join(' ')}`.lines.map { Entry.parse _1 }.compact | |
entries.each(&:move) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning: May overwrite files whose paths are identical up to the first dot. May cause disastrous results for paths containing a dot in a directory name.