Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This script works fine for all files recursively as well but it does not name files that has space in between. For example it throws error for the files "this is a test.txt" or "test file.txt"

Any idea how to fix it?

   #!/bin/bash
   dir="/data/"
   #for filename in `ls -1t $dir/`
   for filename in `find $dir -type f`
   do
   i=".`date -r $filename +%s`"
   mv $filename $filename$i

   done
share|improve this question

2 Answers 2

Try this instead :

 #!/bin/bash

 shopt -s globstar # require bash4 : recursive

 dir="/data/"
 for filename in $dir**; do
    i=".$(date -r $filename +%s)"
    mv "$filename" "$filename$i"
 done

If you don't have bash4 :

find "$dir" -type f -exec bash -c '
    i=".$(date -r $1 +%s)"
    mv "$1" "$1$i"
' -- {} \;

Don't forget to double quote every variables !

See http://mywiki.wooledge.org/Quotes, http://mywiki.wooledge.org/Arguments and http://wiki.bash-hackers.org/syntax/words.

share|improve this answer
    
shopt: globstar: invalid shell option error –  money 2 days ago
    
Also did you mean for filename in $dir*.* or just ** ? This won't rename any folders right? –  money 2 days ago
    
Have you seen bash4 ? That means you need bash >= 4.*. bash -version –  sputnick 2 days ago
    
Okay updating it. –  money 2 days ago
1  
you should completely drop the globstar bit - it adds nothing but confusion to this - as you 've seen. Probably find is the way to go here. That recursion call is incredibly slow on a large filesystem by the way. And it blows up when symlinks screw up the tree. –  mikeserv 2 days ago

Try a null-delimited while loop instead (and remember to quote all the variable expansions):

#!/bin/bash

dir="/data/"
while IFS= read -r -d '' filename
do
  i="$(date -r "$filename" +%s)"
  mv -- "$filename" "$filename.$i"
done < <(find "$dir" -type f -print0)
share|improve this answer
    
where should I add the directory path? –  money 2 days ago
    
@money I have clarified the answer –  steeldriver 2 days ago
    
Okay this works. But it has 2 dots after file name. I need only one. Instead of "Test filename.txt..1213213" I need it as "Test filename.txt.1213213" –  money 2 days ago
    
@money are you sure you didn't retain an extra . in the expression for i? I moved it for stylistic reasons –  steeldriver 2 days ago
    
I think it did have a . I'm double checking this. –  money 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.