Programing

Ruby에서 파일 이름을 바꾸는 방법은 무엇입니까?

crosscheck 2021. 1. 10. 19:14

Ruby에서 파일 이름을 바꾸는 방법은 무엇입니까?


내 .rb 파일은 다음과 같습니다.

puts "Renaming files..."

folder_path = "/home/papuccino1/Desktop/Test"
Dir.glob(folder_path + "/*").sort.each do |f|
    filename = File.basename(f, File.extname(f))
    File.rename(f, filename.capitalize + File.extname(f))
end

puts "Renaming complete."

파일은 초기 디렉토리에서 .rb 파일이있는 위치로 이동됩니다. 파일을 이동하지 않고 그 자리에서 파일 이름을 바꾸고 싶습니다.

해야 할 일에 대한 제안이 있습니까?


간단히 :

File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))

folder_path는 파일 이름의 일부일 필요가 없습니까?

puts "Renaming files..."

folder_path = "/home/papuccino1/Desktop/Test/"
Dir.glob(folder_path + "*").sort.each do |f|
  filename = File.basename(f, File.extname(f))
  File.rename(f, folder_path + filename.capitalize + File.extname(f))
end

puts "Renaming complete."

편집 : 매트가 약간 다른 방식으로 만 나와 같은 대답을 제공하는 것으로 보입니다.


변경하려는 파일과 동일한 위치에서 실행중인 경우

File.rename("test.txt", "hope.txt")

솔직히, 가끔은 루비를 사용하는 요점을 알지 못합니다 ... 파일 이름이 단순히 쉘에서 해석되는 한 필요하지 않습니다.

`mv test.txt hope.txt`

Linux 파일 시스템을 사용하는 경우 시도해 볼 수 있습니다. mv #{filename} newname

File.rename (old, new)를 사용할 수도 있습니다.


파일 이름을 적절하게 인용 할 준비가되지 않은 경우이 패턴을 사용하지 마십시오.

`mv test.txt hope.txt`

실제로 "hope.txt"대신 "foo the bar.txt"라는 파일이 있다고 가정하면 결과는 예상 한 결과가 아닙니다.

참조 URL : https://stackoverflow.com/questions/5530479/how-to-rename-a-file-in-ruby