0

I have a directory looks like:

dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls
DFT-00001 DFT-00004 DFT-00007 DFT-00010 DFT-00013 DFT-00016 DFT-00019 DFT-00022 DFT-00025 DFT-00028 DFT-00031 DFT-00034
DFT-00002 DFT-00005 DFT-00008 DFT-00011 DFT-00014 DFT-00017 DFT-00020 DFT-00023 DFT-00026 DFT-00029 DFT-00032
DFT-00003 DFT-00006 DFT-00009 DFT-00012 DFT-00015 DFT-00018 DFT-00021 DFT-00024 DFT-00027 DFT-00030 DFT-00033

And inside each folder there is there is a file called Li?Fe?O?_0, however, some of them might overlap, for example:

dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00001/
Li1Fe5O6_0
dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00002/
Li1Fe5O6_0
dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00010/
Li2Fe4O6_0

Now, I want to extract the subfolder out into another directory, The first attempt I try is:

find `pwd` -mindepth 1 -maxdepth 1 -type d -exec sh -c "echo {}; cd {}; ls; cp -r * /Users/wenxuanhuang/Desktop/software/CASM_NEW/LiFeO_from_Alex_2015_08_25/LiFeO2-CE/02-refinement/CE-06-new-stuctures_extracted" \;

However, due to naming conflicts, some of them will overlap each other. what I want is: if they overlap: I want to rename it into something that is not conflicting and copy it inside....

Ideally, Suppose Li1Fe5O6_0 is already in the new folder and I am going to copy another Li1Fe5O6_0 into that, I would like to name the last Li1Fe5O6_0 into Li1Fe5O6_1 and copy that Li1Fe5O6_1 inside (in the future, we might have Li1Fe5O6_1 Li1Fe5O6_2 Li1Fe5O6_3 etc.) But if this version of code is too tedious. Then it doesn't matter...

1

This should do:

#!/bin/bash

# this is the crucial setting: replace a glob pattern that matches zero files
# with nothing (the default is to *not* replace the pattern at all)
shopt -s nullglob

destination=/some/directory

unique_filename() {
    local root=${1%_*}_
    local files=( "$destination/$root"* )
    echo "$destination/${root}${#files}"
}

cd /wherever/you/need/to/go

for f in */Li?Fe?O?_0; do
    echo mv "$f" "$(unique_filename "$(basename "$f")")"
done

It works by counting the number of files in the destination directory matching, for example, "Li1Fe5O6_*". If there are none, use "Li1Fe5O6_0". If "Li1Fe5O6_0" is already present, the $files array will have one element, so the unique filename will then be "Li1Fe5O6_1"

  • This is incredibly complex, Thank you very much ! :) – user40780 Aug 31 '15 at 18:40

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.