Batch Copy Existing File Names with New Folder Names: Move Files and Create Folders

Abstract: Batch move files into new folders named after the source file using cross-platform Bash and PowerShell scripts.

Created: 2026-09-28 by
This article provides concrete, cross-platform solutions for batch moving files into new folders named after the source file. You will find ready-to-use command-line scripts for Linux, macOS, and Windows PowerShell that automate directory creation and file relocation without manual intervention or third-party tools.

Linux and macOS Solution Using Bash

On Unix-like systems, the most robust method involves a simple Bash loop combined with mkdir and mv. This approach ensures that each file gets its own directory before being moved, preventing errors if multiple files share similar prefixes. The following script iterates through all files in the current directory, extracts the base name (excluding extension), creates a folder with that name, and moves the file into it.
for file in *; do
  # Skip directories to avoid recursion errors
  [ -d "$file" ] && continue
  
  # Extract filename without extension
  name="${file%.*}"
  
  # Create directory if it doesn't exist
  mkdir -p "$name"
  
  # Move the file into the new directory
  mv "$file" "$name/"
done
This code is safe because it uses -d to check if an item is already a directory, which prevents the script from trying to move a folder into itself or creating nested loops. The ${file%.*} parameter expansion removes the shortest match of .* from the end of the variable, effectively stripping the file extension. If you need to preserve the original structure while copying instead of moving, replace mv with cp. For large batches, this method is efficient but processes files sequentially. If you require parallel processing for thousands of files, consider using GNU Parallel, but for standard use cases, this loop is sufficient and easy to audit. For more complex scenarios involving recursive directory traversal, you might want to explore related techniques such as those discussed in our guide on managing files in dual-boot environments, which often requires careful handling of path separators and case sensitivity across operating systems. See Dual-Booting Linux (Manjaro) and Windows for insights on cross-platform file management challenges.

Windows Solution Using PowerShell

PowerShell offers a native way to achieve this without external dependencies. The Move-Item cmdlet can be combined with New-Item to create the target directories dynamically. Unlike older CMD batch scripts, PowerShell handles path construction more elegantly and avoids common pitfalls with spaces in filenames.
Get-ChildItem -File | ForEach-Object {
    $folderName = $_.BaseName
    $targetPath = Join-Path -Path $_.Directory -ChildPath $folderName
    
    # Create the directory if it does not exist
    if (-not (Test-Path -Path $targetPath)) {
        New-Item -ItemType Directory -Path $targetPath -Force
    }
    
    # Move the file
    Move-Item -Path $_.FullName -Destination $targetPath
}
The Get-ChildItem -File command ensures that only files are processed, ignoring existing subdirectories. $_.BaseName retrieves the filename without the extension, mirroring the behavior of the Bash example. Join-Path safely concatenates the directory path and the new folder name, handling trailing slashes automatically. The Test-Path check prevents errors if the script is run twice, ensuring idempotency. Note that Move-Item will overwrite existing items in the destination if they have the same name, so always verify your directory contents before running bulk operations. If you frequently work with image files from cameras, you may benefit from specialized renaming scripts that incorporate creation dates rather than just base names. Check out our tutorial on BASH Script to Copy Image Files Recursively from Camera Folders and Rename with Creation Date for advanced date-based organization strategies.

Handling Edge Cases and Safety

Regardless of the platform, certain edge cases can cause data loss if not handled correctly. First, always test your script on a small subset of files or a duplicate directory before applying it to critical data. Second, be aware of character restrictions. Some operating systems restrict characters like :, *, or ? in folder names. If your filenames contain these characters, you must sanitize them before using them as folder names. In Bash, you can use tr to replace invalid characters: name=$(echo "$file" | tr -d ':*?'). In PowerShell, you can use regex replacement: $folderName = $folderName -replace '[*:?\"<>|]', ''. Third, consider what happens if two files have the same base name but different extensions (e.g., report.pdf and report.docx). Both would attempt to create a folder named report. The first file succeeds, but the second file’s move operation will succeed into the existing folder, potentially causing confusion. To avoid this, you might choose to include the extension in the folder name or skip duplicates. A simple fix in Bash is to append the extension: name="${file%.*}_${file##*.}". Finally, ensure you have adequate disk space and permissions. Moving files within the same filesystem is fast, but if you are moving files across network drives or different partitions, the operation may take longer and fail due to permission issues. Always run these scripts with appropriate user privileges. If you encounter issues where files seem missing after a move, verify that you are looking in the correct parent directory, as sometimes scripts execute in unexpected working directories. For troubleshooting file visibility issues, refer to our article on Find Command Not Finding Files to understand how path resolution works in terminal environments.

Frequently Asked Questions

Will this script delete my original files?

Yes, the mv and Move-Item commands relocate files, meaning they are removed from the source directory and placed in the new folder. If you wish to keep copies in the original location, replace mv with cp in Bash or Copy-Item in PowerShell.

How do I handle files with no extension?

The provided scripts rely on ${file%.*} or $_.BaseName, which return the full filename if no extension exists. This means files without extensions will create folders named exactly like the file itself. Ensure this is acceptable for your workflow, or add a check to skip such files.

Can I run this on subdirectories recursively?

The basic examples only process files in the current directory. To process recursively, add -R to Get-ChildItem in PowerShell or use find . -type f in Bash. However, be cautious as this can create deeply nested structures if not carefully managed.

What if two files have the same base name?

If two files share the same base name (e.g., data.csv and data.xlsx), both will move into a folder named data. This is generally safe, but if you want separate folders, modify the script to include the extension in the folder name, such as data_csv.

Is there a GUI alternative for non-command-line users?

While command-line tools offer precision, GUI file managers like Total Commander or FreeCommander support batch operations. Look for features labeled "Batch Rename" or "Move to Folder Based on Name," though they may not offer the exact same flexibility as custom scripts for creating new folders dynamically.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More