0

This is my current code:

Base_DIR=/file/path
other= /folder/path
find "Base_DIR" -type f -name "*.txt"
while IFS= read -r file; do
year="$(date -d "$(stat -c %y "$file")" +%Y
month="$(date -d "$(stat -c %y "$file")" +%m
day="$(date -d "$(stat -c %y "$file")" +%d

[[ ! -d "$other/$year/$month/$day" ]] && mkdir -p "$other/$year/$month/$day";

mv "$file" "$other/$year/$month/$day`

So it basically finds the files from different sub-directories and moves the file into a different folder while creating a folder depending on the year, month and day of when the file was last modified.

My question is how can i add to this so when i move files with the same name it will automatically rename the file to, for example file(1).txt. Right now the code only copies 1 of the files and not both.

Thank you.

  • 1
    The current code does not work. You have multiple errors in it, including spaces after a = and no done at the end of the loop. You're presumably wanting to pipe the result of the find command into the loop, right? You also seem to miss $ on $Base_DIR. – Kusalananda Apr 23 at 18:39
  • install and use shellcheck. – ctrl-alt-delor Apr 23 at 18:52
0

Notwithstanding that the code in your question does not work at all, to address the question of "how can I nondestructively move a file by adding a numerical suffix", something akin to this might work:

$ cat mvr.sh
#!/usr/bin/env bash

bail() {
   retcode=$1
   shift
   printf "%s" "$*" 1>&2
   exit "$retcode"
}

[[ -f "$1" ]] || bail 1 "File '$1' not found"

if ! [[ -f "$2" ]]; then
   mv "$1" "$2"
else
   if [[ -d "$2" ]]; then
      $0 "$1" "${2}/${1}"
      exit $?
   else
      suffix=1
      until ! [[ -f "${2}.$suffix" ]]; do
         suffix=$((suffix+1))
      done
      mv "$1" "${2}.$suffix"
   fi
fi

In action:

$ ls
bar    bar.1  bar.2  mvr.sh
$ touch foo; ls
bar    bar.1  bar.2  foo    mvr.sh
$ ./mvr.sh foo bar
$ ls
bar    bar.1  bar.2  bar.3  mvr.sh

The real meat of how do do this starts at the if statement.

  • If the destination filename doesn't yet exist, great, just mv.
  • If it exists and is a directory, great: write into that directory by recursing.
  • If it exists and is a file, start trying new numerical suffixes until we find one that's not already present.
0

With

mv --backup=t file directory/

You should get files named file, file.~1~, file.~2~, etc.

  • Great! this works! – Eric Hong Apr 24 at 13:36
  • Happy to know it! Please consider accepting (and eventually upvoting) the answer, as people interested in the question will see it has an accepted answer. – sgorblex Apr 25 at 15:29

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.