How to mass rename files in ruby

前端 未结 5 1179
梦谈多话
梦谈多话 2021-02-20 02:21

I have been trying to work out a file rename program based on ruby, as a programming exercise for myself (I am aware of rename under linux, but I want to learn Ruby, and rename

5条回答
  •  甜味超标
    2021-02-20 03:16

    Your problem is that gets returns a newline at the end of the string. So, if you type "foo" then searchPattern becomes "foo\n". The simplest fix is:

    searchPattern = gets.chomp
    

    I might rewrite your code slightly:

    $stdout.sync
    print "Enter the file search query: "; search  = gets.chomp
    print "Enter the target to replace: "; target  = gets.chomp
    print "  Enter the new target name: "; replace = gets.chomp
    Dir['*'].each do |file|
      # Skip directories
      next unless File.file?(file)
      old_name = File.basename(file,'.*')
      if old_name.include?(search)
        # Are you sure you want gsub here, and not sub?
        # Don't use `old_name` here, it doesn't have the extension
        new_name = File.basename(file).gsub(target,replace)
        File.rename( file, new_path )
        puts "Renamed #{file} to #{new_name}" if $DEBUG
      end
    end
    

提交回复
热议问题