Question

(I'm in a Bash environment, Cygwin on a Windows machine, with awk, sed, grep, perl, etc...) I want to add the last folder name to the filename, just before the last underscore (_) followed by numbers or at the end if no numbers are in the filename.

Here is an example of what I have (hundreds of files needed to be reorganized) :

./aaa/A/C_17x17.p
./aaa/A/C_32x32.p
./aaa/A/C.p
./aaa/B/C_12x12.p
./aaa/B/C_4x4.p
./aaa/B/C_A_3x3.p
./aaa/B/C_X_91x91.p
./aaa/G/C_6x6.p
./aaa/G/C_7x7.p
./aaa/G/C_A_113x113.p
./aaa/G/C_A_8x8.p
./aaa/G/C_B.p
./aab/...

I would like to rename all thses files like this :

./aaa/C_A_17x17.p
./aaa/C_A_32x32.p
./aaa/C_A.p
./aaa/C_B_12x12.p
./aaa/C_B_4x4.p
./aaa/C_A_B_3x3.p
./aaa/C_X_B_91x91.p
./aaa/C_G_6x6.p
./aaa/C_G_7x7.p
./aaa/C_A_G_113x113.p
./aaa/C_A_G_8x8.p
./aaa/C_B_G.p
./aab/...

I tried many bash for loops with sed and the last one was the following :

IFS=$'\n'
for ofic in `find * -type d -name 'A'`; do
  fic=`echo $ofic|sed -e 's/\/A$//'`
  for ftr in `ls -b $ofic | grep -E '.png$'`; do
    nfi=`echo $ftr|sed -e 's/(_\d+[x]\d+)?/_A\1/'`
    echo mv \"$ofic/$ftr\" \"$fic/$nfi\"
  done
done

But yet with no success... This \1 does not get inserted in the $nfi... This is the last one I tried, only working on 1 folder (which is a subfolder of a huge folder collection) and after over 60 minutes of unsuccessful trials, I'm here with you guys.

Was it helpful?

Solution

I modified your script so that it works for all your examples.

IFS=$'\n'
for ofic in ???/?; do
  IFS=/ read fic fia <<<$ofic
  for ftr in `ls -b $ofic | grep -E '\.p.*$'`; do
    nfi=`echo $ftr|sed -e "s/_[0-9]*x[0-9]*/_$fia&/;t;s/\./_$fia./"`
    echo mv \"$ofic/$ftr\" \"$fic/$nfi\"
  done
done

OTHER TIPS

# it's easier to change to here first
cd aaa
# process every file
for f in $(find . -type f); do
  # strips everything after the first / so this is our foldername
  foldername=${f/\/*/}
  # creates the new filename from substrings of the
  # original filename concatenated to the foldername 
  newfilename=".${f:1:3}${foldername}_${f:4}"
  # if you are satisfied with the output, just leave out the `echo`
  # from below
  echo mv ${f} ${newfilename}
done

Might work for you.

See here in action. (slightly modified, as ideone.com handles STDIN/find diferently...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top