Thursday, March 19, 2015

Recursively change file extension

Here's a technique you can use to recursively change the file extension of all files with a particular file extension, e.g., ".txt", to another one, e.g., ".js".

It leverages another technique discussed in the Process Array of Values in Bash Shell post.

It's a one liner, assuming you have a change-file-ext script.

One liner


$ for dir in "${dirs[@]}"; do (cd "$dir"; change-file-ext txt js)  ; done


change-file-ext script


#!/usr/bin/env ruby

# filename:  change-file-ext
# author:    Lex Sheehan
# copyright: Lex Sheehan LLC
# license:   GPL
# status:    production
# comments:  changes file extensions in current directory

def usage
  puts 'Usage:   change-file-ext  '
  puts 'Example: change-file-ext "css.erb" "css"'
  exit
end

if ARGV.size < 2 || ARGV.include?('--h')
  usage
else
  from_ext = "*.#{ARGV[0]}"
  to_ext = ARGV[1]
end

Dir.glob(from_ext).each{|i| `mv #{i} #{i.slice(0..-from_ext.size)}.#{to_ext}` }


References

http://lexsheehan.blogspot.com/2014/05/process-array-of-values-in-bash-shell.html


Share this article



This work is licensed under the Creative Commons Attribution 3.0 Unported License.

No comments:

Post a Comment