SFTP Rename (mv) with Wildcard

Abstract: Resolve SFTP wildcard rename errors by using local shell loops to generate batch commands for individual file renaming.

Created: 2026-09-24 by
The SFTP protocol does not support wildcard expansion for the rename (or mv) command because the server processes commands literally without shell interpretation. To rename multiple files efficiently, you must use a client-side loop in your local shell or script to iterate through the matching files and execute individual rename commands for each one. This approach ensures that every file is processed correctly while adhering to the strict syntax requirements of the SFTP subsystem.

Understanding SFTP Command Limitations

When you connect to an SFTP server, you are interacting with a remote subsystem that mimics basic file operations but lacks the intelligence of a full Linux shell. The rename command in SFTP corresponds directly to the POSIX rename() system call, which expects exactly two arguments: the source path and the destination path. Unlike the local mv command in Bash or Zsh, the SFTP client does not pass wildcards like *.txt to the server for expansion. If you attempt to run rename *.txt backup_*.txt, the server will look for a literal file named *.txt, which almost certainly does not exist, resulting in a "No such file" error. This limitation exists for security and consistency reasons. Allowing server-side globbing could lead to unexpected behavior if the directory structure changes between the time the client sends the pattern and the time the server processes it. It also prevents potential security issues where a maliciously crafted filename could exploit shell injection vulnerabilities. Therefore, the responsibility for expanding patterns falls entirely on the client side.

Using Local Shell Loops for Batch Renaming

The most robust solution is to handle the wildcard expansion locally before sending commands to the SFTP session. You can achieve this by using a for loop in your terminal. This method allows you to preview the changes and control the flow precisely. For example, if you want to add a prefix to all .log files in the current directory, you can use the following structure in your bash shell:
for file in *.log; do
  echo "Renaming $file to prefix_$file"
  # In a real script, you would pipe this to sftp or use expect
done
However, since SFTP requires an interactive session or a specific batch mode, you need to integrate this loop with the SFTP command. One effective way is to generate a batch file dynamically. You can create a temporary script that contains the sequence of rename commands.
#!/bin/bash
SFTP_USER="user"
SFTP_HOST="example.com"
REMOTE_DIR="/remote/path"

# Generate batch commands
{
  echo "cd $REMOTE_DIR"
  for file in *.log; do
    echo "rename $file prefix_${file}"
  done
} > /tmp/sftp_rename_batch.txt

# Execute SFTP with batch mode
sftp -b /tmp/sftp_rename_batch.txt ${SFTP_USER}@${SFTP_HOST}
This script first constructs a list of commands. The cd command ensures you are in the correct remote directory. Then, for each file matched by the local wildcard, it appends a rename instruction to the batch file. Finally, it executes the SFTP connection using the -b flag, which reads commands from the specified file. This method is efficient, safe, and easy to debug because you can inspect /tmp/sftp_rename_batch.txt before running the actual transfer.

Alternative: Using SSH for Remote Shell Execution

If you have SSH access to the server and trust the environment, you can bypass SFTP limitations entirely by executing the mv command remotely via SSH. The SSH protocol provides a full shell environment, which supports wildcards natively. You can use the ssh command with a single-line command string:
ssh [email protected] 'cd /remote/path && for f in *.log; do mv "$f" "prefix_${f}"; done'
This approach is often simpler for sysadmins who already have SSH keys configured. However, it requires that the user has write permissions in the target directory and that the SSH daemon is enabled. Note that this method does not use the SFTP subsystem, so it may behave differently regarding file locking or atomic operations depending on the server's configuration. For users restricted to SFTP-only access, as discussed in our guide on SSH User chroot Jail: Restricting SFTP Access to Specific Directory, this SSH method might not be available due to permission constraints.

Handling Errors and Edge Cases

When renaming multiple files, errors can occur if a destination file already exists. The standard rename command in SFTP will fail if the target name is occupied. To avoid stopping the entire batch process, you should check for existing files before attempting the rename. In the local loop approach, you can add a conditional check:
for file in *.log; do
  dest="prefix_${file}"
  # Check if destination exists locally? No, we need remote check.
  # SFTP doesn't have a simple 'exists' command in batch mode easily.
  # A safer bet is to catch errors or use unique names.
  echo "rename $file $dest"
done
Since SFTP batch mode does not provide easy feedback on individual command success within the loop generation phase, consider using unique timestamps or UUIDs for new filenames if conflicts are likely. Alternatively, use the ls command in SFTP to verify the remote state before generating the batch file. Another edge case involves filenames with spaces or special characters. Always quote your variables in the local shell script to prevent word splitting. In the SSH method, ensure proper escaping of quotes within the remote command string.

Performance Considerations

For thousands of files, generating a massive batch file might consume significant memory. In such cases, streaming the commands directly into SFTP is more memory-efficient. You can use process substitution or pipes to feed commands directly:
(echo "cd /remote/path"; for file in *.log; do echo "rename $file prefix_${file}"; done) | sftp [email protected]
This technique avoids creating intermediate files on disk and works well for moderate numbers of files. However, for very large datasets, consider using tools like rsync or specialized migration scripts that handle concurrency and error recovery better than simple SFTP loops.

Frequently Asked Questions

Why does my SFTP client ignore the asterisk symbol?

The SFTP protocol treats the rename command as a literal operation between two specific paths. It does not invoke a shell on the server side to expand wildcards. Consequently, the server looks for a file literally named with an asterisk, which usually fails.

Can I use wildcards with the get or put commands in SFTP?

No, the get and put commands in standard SFTP also require explicit file names. They do not support globbing patterns. You must either specify each file individually or use a client-side tool like lftp or curl that supports recursive transfers with pattern matching.

What happens if the destination file already exists during a rename?

The SFTP rename command will fail with an error if the target path already exists. It does not overwrite existing files by default. You must manually remove the old file or choose a different destination name to proceed.

Is there a way to rename files recursively in SFTP?

Standard SFTP does not have a recursive rename command. You would need to navigate into subdirectories using cd and then apply the rename logic to each level, or write a script that traverses the directory tree and generates rename commands for all nested files.

How can I troubleshoot empty file uploads related to SFTP sessions?

If you are experiencing issues with file integrity after moving or renaming, ensure that the transfer completes fully before disconnecting. For upload-specific problems, refer to our guide on Troubleshooting: Curl SFTP Uploads Empty File without Error to diagnose connectivity or buffer issues.

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