1

I have the files names as below in a directory

example1.1.timestamp(.1457644337)
example1.2.timestamp
example1.3.timestamp

and so on about 100 files. I need to rename all the files by removing the .timestamp(.1457644337) at the end.

I managed to do it for a single file

ls -l filename | sed 's/\.[^.]*$//'
  • isn't for file in *;do ..rename here..;done an option ? – MelBurslan Mar 11 '16 at 17:33
4

Using rename (prename):

  • If the timestamp is same for all files, from the directory containing the files you can do:

    rename -n 's/\.1457644337$//' example1.*.*
    
  • For varying timestamps:

    rename -n 's/\.\d+$//' example1.*.*
    

Recursively:

find . -type f -name 'example1.*.*' -exec rename -n 's/\.\d+$//' {} +

Remove -n (dry-run) if you are satisfied with the changes to be made.

Note that, this will remove the last portion containing digits including .. So if you have just any random number apart from timestamp that will be removed too.


Using shell parameter expansion:

  • If the timestamp is same for all files:

    for file in *.*; do mv -i "$file" "${file%.1457644337}"; done
    
  • For varying timestamps, assuming bash (other advanced shells have similar options) :

    shopt -s extglob; for file in *.*; do mv -i "$file" "${file%.+([0-9])}"; done
    

Recursively:

find . -type f -name 'example1.*.*' -exec \
    bash -ic 'shopt -s extglob; mv -i "$1" "${1%.+([0-9])}"' _ {} \;

Here i have used extglob shell option to match the digits after last . by using pattern +([0-9]) hence the replacement parameter expansion pattern becomes ${file%.+([0-9])}.

Again this does not strictly matches a timestamp. Although you can modify the pattern to get robustness if you have any precise format for the timesatmps.

  • @tradersjoe No problem.. Please select the answer as accepted by clicking the tick mark on the left of the answer so that this issue can be marked as solved.. – heemayl Mar 11 '16 at 18:17
0

interactive way, with visual inspecting commands:

ls | vim -

inside vim:

:%s/.*/mv \0 \0/        ...move filename filename
:%s/\.[^.]*$//          ...same as your sed regex
:w !sh                  ...run buffer with shell
:q!                     ...close without saving

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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