Py-ser
Py-ser

Reputation: 2098

Renaming file with portion of parent's directory name

I have many directories named 201801XX_samename_stillsame where XX changes and the rest stay the same. Within are files that all have the same name, e.g. filename.png. I would need a bash script to change the filename.png according to the variable portion of the directory's name, e.g.

for file in **_samename_stillsame/; do
    #extract portion of the name as e.g., $date
    cp filename.png "$date".png

Upvotes: 0

Views: 65

Answers (4)

lee-pai-long
lee-pai-long

Reputation: 2282

for d in $(ls -d 2018*_samename_stillsame); do 
  mv $d/{filename,$(echo "$d" | cut -d '_' -f1)}.png; 
done

EDIT: Based on @kamil-cuk answer and because I didn't realise you just wanted the XX part

for d in $(ls -d 2018*_samename_stillsame); do 
  mv $d/{filename,${d:6:2}}.png; 
done

In my case when testing the index actually start at 0 not 1 so to have the seventh character you need to slice at 6

Upvotes: 2

Walter A
Walter A

Reputation: 20002

Find all directory names, use sed to construct a mv command and the e option to execute the constructed command.

find 201801* -maxdepth 1 -type d | 
   sed -r 's#201801(..)_samename_stillsame#mv &/filename.png &/\1.png#e'

Upvotes: 1

anubhava
anubhava

Reputation: 785126

You may use:

shopt -s nullglob
kn='_samename_stillsame/'

for f in **"$kn"; do
   mv -- "$f/filename.png" "$f${f%%$kn}.png"
done

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 141000

for dir in 201801*_samename_stillsame/; do
    cp "$dir/filename.png" "${dir:7:2}.png"
done

for each directory copy the file. The ${dir:7:2} is a substring of the variable, 2 characters from the 7th character (ie. the 'XX' part).

Upvotes: 2

Related Questions