Flattening a WordPress Uploads Directory with Bash

Managing WordPress media files can be messy — especially when your uploads directory grows into a maze of nested year/month folders. This guide shows you how to flatten your entire uploads tree into a single folder using a simple Bash script, while safely handling duplicate filenames with automatic versioning.

Table of Contents

 

If you’ve worked with a WordPress site, you know that media files get stored in a nested year/month directory structure under wp-content/uploads. For example:

This structure is great for WordPress, but sometimes you need a single flat folder with all the files — for example, when migrating media, preparing datasets, or reviewing images in bulk.

The challenge? If the same filename exists in multiple places, simply copying everything into one folder risks overwriting files.


The Solution: A Bash Script

Here’s a lightweight Bash script that flattens a directory tree into a single folder, while automatically handling duplicate filenames by appending version numbers (_v1, _v2, etc.) after the extension.


How It Works

  • find "$SRC_DIR" -type f → Recursively finds all files in the WordPress uploads directory.
  • basename "$f" → Strips away the path so we’re left with just the filename.
  • Duplicate handling → If the filename already exists in the flat folder, the script creates file.jpg_v1, file.jpg_v2, etc.
  • Safe copy → Uses cp instead of mv, so your original uploads remain intact.

Usage

  1. Save the script as flatten_copy.sh.
  2. Make it executable:
  3. Run it with defaults (source: ./wp-content/uploads, destination: ./flat_output):
  4. Or specify custom source/destination:

Example Output

If your uploads folder contains duplicate files:

The flattened folder will contain:

If a third duplicate exists, it will become:


Why This Is Useful

Flattening your uploads folder is handy when:

  • Migrating media between WordPress sites.
  • Exporting assets for use in a different CMS.
  • Preparing datasets for machine learning or bulk optimization.
  • Quickly reviewing images without navigating nested folders.

With just a few lines of Bash, you can save hours of manual work.


Pro Tip: For very large sites, swap cp for rsync or mv depending on whether you need a copy or move.

Have a project or a problem?

Talk with a senior engineer for practical recommendations—no obligation.

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Categories

Get a free consultation from Reliable Penguin

Submit the form—or for immediate service call 866-649-7984.