Created
January 29, 2009 15:11
-
-
Save Narnach/54572 to your computer and use it in GitHub Desktop.
Execute a command for each of the provided files, or to all files in the current directory
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/env ruby | |
| # eachfile.rb - Execute a command for each file | |
| def help | |
| puts <<-HELP | |
| Syntax: #{$0} [option] "COMMAND" File1 [File2] .. [FileN] | |
| The command is executed for each of the specified files. | |
| FILE in the command is substituted with the name of each file. | |
| If there is no FILE in command, the filename is given as parameter instead. | |
| When no files are provided, all files in the current directory are used. | |
| The following optional options are not treated as a command: | |
| -h, --help: Show this help screen | |
| -V, --verbose: Be more verbose | |
| HELP | |
| end | |
| def error(msg) | |
| help | |
| puts "Error: %s" % msg | |
| exit 1 | |
| end | |
| class String | |
| def indent(depth=2) | |
| self.split("\n").map{|line| " "*depth + line}.join("\n") | |
| end | |
| end | |
| raw_cmd = ARGV.shift.to_s | |
| case raw_cmd | |
| when '-V', '--verbose' | |
| @verbose = true | |
| when '-h', '--help' | |
| help | |
| exit 0 | |
| else | |
| @no_options = true | |
| end | |
| raw_cmd = ARGV.shift.to_s unless @no_options | |
| error("no command was provided") unless raw_cmd.size>0 | |
| files = ARGV | |
| if files.size == 0 | |
| files = Dir.glob('*').select {|f| File.file?(f)} | |
| end | |
| do_substitute = raw_cmd.grep('FILE').size>0 | |
| files.each do |file| | |
| if do_substitute | |
| cmd = raw_cmd.gsub('FILE',file) | |
| else | |
| cmd = raw_cmd + ' ' + file | |
| end | |
| puts "Execute: #{cmd}" if @verbose | |
| puts `#{cmd}`.indent(@verbose ? 2 : 0) | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment