Rename multiple files based on pattern in Unix

前端 未结 22 1138
死守一世寂寞
死守一世寂寞 2020-11-22 06:31

There are multiple files in a directory that begin with prefix fgh, for example:

fghfilea
fghfileb
fghfilec

I want to rename a

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:03

    It was much easier (on my Mac) to do this in Ruby. Here are 2 examples:

    # for your fgh example. renames all files from "fgh..." to "jkl..."
    files = Dir['fgh*']
    
    files.each do |f|
      f2 = f.gsub('fgh', 'jkl')
      system("mv #{f} #{f2}")
    end
    
    # renames all files in directory from "021roman.rb" to "021_roman.rb"
    files = Dir['*rb'].select {|f| f =~ /^[0-9]{3}[a-zA-Z]+/}
    
    files.each do |f|
      f1 = f.clone
      f2 = f.insert(3, '_')
      system("mv #{f1} #{f2}")
    end
    

提交回复
热议问题