Skip to content

Instantly share code, notes, and snippets.

@AbeEstrada
Created August 6, 2024 05:03
Show Gist options
  • Save AbeEstrada/71c3a23d06767b2ed6b3ec0325d414c1 to your computer and use it in GitHub Desktop.
Save AbeEstrada/71c3a23d06767b2ed6b3ec0325d414c1 to your computer and use it in GitHub Desktop.
Move half of the files to one directory
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <source_directory> <destination1> <destination2>"
exit 1
fi
# Assign arguments to variables
source_dir="$1"
dest_dir1="$2"
dest_dir2="$3"
# Check if source directory exists
if [ ! -d "$source_dir" ]; then
echo "Error: Source directory does not exist"
exit 1
fi
# Create destination directories if they don't exist
mkdir -p "$dest_dir1" "$dest_dir2"
# Get the total number of files
total_files=$(find "$source_dir" -maxdepth 1 -type f | wc -l)
half_files=$((total_files / 2))
# Create a sorted list of all files
sorted_files=$(find "$source_dir" -maxdepth 1 -type f | sort)
# Move the first half of the files to destination1
echo "$sorted_files" | head -n "$half_files" | while read -r file; do
mv "$file" "$dest_dir1"
echo "Moved to $dest_dir1: $file"
done
# Move the remaining files to destination2
echo "$sorted_files" | tail -n +"$((half_files + 1))" | while read -r file; do
mv "$file" "$dest_dir2"
echo "Moved to $dest_dir2: $file"
done
echo "Files have been split between $dest_dir1 and $dest_dir2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment