Score:0

A bash script to rename files from different directories at once

us flag

If I have a directory named /all_images, and inside this directory there's a ton of directories, all the directories named as dish_num as shown below. and inside each dish directory, there's one image named rgb.png. How can i rename all the image files to be the name of its directory.

Before

|
├── dish_1
│   └── rgb.png
├── dish_2
│   └── rgb.png
├── dish_3
│   └── rgb.png
├── dish_4
│   └── rgb.png
└── dish_5
    └── rgb.png

After

|
├── dish_1
│   └── dish_1.png
├── dish_2
│   └── dish_2.png
├── dish_3
│   └── dish_3.png
├── dish_4
│   └── dish_4.png
└── dish_5
    └── dish_5.png
Score:3
hr flag

A simple shell loop should suffice:

for d in dish_*; do 
  echo mv "$d/rgb.png" "$d/$d.png"
done

or (if you need to run it from somewhere other than the containing directory)

for d in path/to/dish_*; do 
  f="${d##*/}.png"
  echo mv "$d/rgb.png" "$d/$f"
done

Remove the echo once you are satisfied that it is going to do the right thing.


If you wanted to get fancy, you could do something like this with GNU parallel:

parallel echo mv {}/rgb.png {}/{/.}.png ::: path/to/dish_*

or (if the argument list is too long)

printf '%s\0' path/to/dish_* | parallel --null echo mv {}/rgb.png {}/{/.}.png
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.