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.

2
  • 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. Commented Apr 23, 2019 at 18:39
  • install and use shellcheck. Commented Apr 23, 2019 at 18:52

2 Answers 2

1

With

mv --backup=t file directory/

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

1
  • Great! this works! Commented Apr 24, 2019 at 13:36
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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.