Sunday, May 5, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 5769  / 2 Years ago, wed, december 15, 2021, 3:17:19

I have a main directory that has four folders f1, f2, f3 and f4 each of these folders has 10 folders, and each of these 10 folders ff1...ff10 has some .jpeg images with some names lets say image1.... and so on. What I want to know is how to rename these .jpeg images in each of these folders of the 10 folders in each of f1, f2, f3 and f4, so that I will concatenate the parent folders in the beginning of its name, for example of image1.jpeg is located in f3/ff1 then its name will be f3_ff1_image1.jpeg, same with all the other images in the other 10 folders in each of the four main folders. If anyone can please advise how this can be done in a .sh file.


More From » command-line

 Answers
7

Create a simple file changeName.sh as follow:



    #!/bin/bash
fileName=$(basename $1)
filepath=$(dirname $1)
secondDir=$(basename $filepath)
firstDir=$(basename $(dirname $filepath))
parentDir=$(basename $(dirname $(dirname $filepath)))
mv $1 $filepath/${parentDir}_${firstDir}_${secondDir}_$fileName


save it, for example in /home/yourUser/bin.



Change permission to changeName.sh:



chmod +x /home/yourUser/bin/changeName.sh


Open you /home/yourUser/.bashrc file and add at the end this line:



PATH=$PATH:/home/yourUser/bin


save it and reload it:



source .bashrc


Now you have a new utility that can change name to file using folder as part of name.



Try this:



find mainDirectory -name "*.jpeg" -exec changeName.sh {} ;


mainDirectory can be absolute or relative.



Tested on lubuntu 12.04






dirname strip last component from file name while basename strip directory and suffix from filenames.



So to get third level of directory:



   parentDir=$(basename $(dirname $(dirname $filepath)))

[#23037] Wednesday, December 15, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gavgenerati

Total Points: 120
Total Questions: 126
Total Answers: 119

Location: Marshall Islands
Member since Wed, Feb 9, 2022
2 Years ago
;