1

This command will move the contents of one or more folders to the parent folder. But if there are identical file names with the same extension then there will be files that are overwritten during the move.

find . - mindepth 2 -type f -exec mv "{}" . \; && fin d . - type d -empty -delete

How can I modify this command so that any files with duplicate file names won't be overwritten but will be appended with (1), (2), (3), et cetera?

2 Answers 2

2

There's an option called numbered in mv:

  numbered, t
  make numbered backups

Take a look at the mv man page

You can incorporate that into your one liner.

3
  • I've tried to incorporate it: find . - mindepth 2 -type f -exec mv --backup=numbered -t "{}" . \; && find . -type d -empty -delete It's not working. Any suggestions? I've tried about 6 other placements and it doesn't work.
    – whitewings
    Jul 16, 2015 at 19:27
  • find . -mindepth 2 -type f | xargs mv --backup=numbered -t . && find . -type d -empty -delete
    – neuron
    Jul 16, 2015 at 19:52
  • @Tx but there must be some mistake in there. It overwrites the files with the same name.
    – whitewings
    Jul 17, 2015 at 0:17
0

Copy this script to the top directory where you want all the files to be, make it executable and run it:

#!/bin/bash

## Get a list of all files
list=$(find . -mindepth 2 -type f -print)
nr=1

## Move all files that are unique
find . -mindepth 2 -type f -print0 | while IFS= read -r -d '' file; do
    mv -n $file ./
done
list=$(find . -mindepth 2 -type f -print)

## Checking which files need to be renamed
while [[ $list != '' ]] ; do
   ##Remaming the un-moved files to unique names and move the renamed files
   find . -mindepth 2 -type f -print0 | while IFS= read -r -d '' file; do
       current_file=$(basename $file)
       mv -n $file "./${nr}${current_file}"
   done
   ## Incrementing counter to prefix to file name
   nr=$((nr+1))
   list=$(find . -mindepth 2 -type f -print)
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .