osx - Why is my bash randomly selecting files and renaming? -


on mac terminal scripting increment rename of files in folder. files have number @ end top down approach in order:

foobar101.png foobar107.png foobar115.png foobar121.png foobar127.png foobar133.png foobar141.png foobar145.png foobar151.png foobar155.png 

when create , run loop works:

dir="/customlocation/on/mac" add=1; thefile in $(find $dir -name "*.png" );     cd $dir     mv -v "${thefile}" foobar"${add}".png     ((add++))   done 

however, when runs increment it's not expected:

foobar101.png -> need foobar1.png foobar10.png foobar107.png -> need foobar2.png foobar3.png foobar115.png -> need foobar3.png foobar4.png foobar121.png -> need foobar4.png foobar2.png foobar127.png -> need foobar5.png foobar9.png foobar133.png -> need foobar6.png foobar6.png foobar141.png -> need foobar7.png foobar1.png foobar145.png -> need foobar8.png foobar5.png foobar151.png -> need foobar9.png foobar8.png foobar155.png -> need foobar10.png foobar7.png 

ive tried searching on so, linux/unix, ask ubuntu, , superuser don't see questions solve issue of controlling increment , dont know if it's in particular should looking at. how can control increment lowest number/filename instead of mac possibly randomly renaming increment desired output?


edit:

after comment etan looking numerical values @ end , of files named foobarxxxx , issue. below answer, while awesome , new approach still produces same outcome because of other files. if remove files foobarxxxx , leave files values of foobarxxx code , code in fedorqui's answer work. there way can target while in loop process or have target names , test see length of values , adjust accordingly?

you cannot rely on order of find command, uses the order vfs gives them in.

you may, instead, want sort it:

dir="/customlocation/on/mac" add=1; while ifs= read -r thefile;     cd $dir     mv -v "${thefile}" foobar"${add}".png     ((add++))   done < <(find $dir -name "*.png" | sort) #-------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

note uses process substitution, feed while loop:

process substitution form of redirection input or output of process (some sequence of commands) appear temporary file.


Comments