BASH – Replace Space In Filenames With Underscore


The instructions/steps given below worked for me running CentOS. It may very well work for you on other linux distributions, Red Hat-like or otherwise. Please note that if you decide to use these instructions on your machine, you are doing so entirely at your very own discretion and that neither this site,, nor its author is responsible for any/all damage – intellectual or otherwise.

What is BASH?

BASH is a free software Unix shell written for the GNU Project. Its name is an acronym which stands for Bourne-again shell. The name is a pun on the name of the Bourne shell (sh), an early and important UNIX shell written by Stephen Bourne and distributed with Version 7 UNIX circa 1978, and the concept of being born again. BASH was created in 1987 by Brian Fox. In 1990 Chet Ramey became the primary maintainer. BASH is the default shell on most GNU/Linux systems as well as on Mac OS X and it can be run on most UNIX-like operating systems. It has also been ported to Microsoft Windows using the POSIX emulation provided by Cygwin, to MS-DOS by the DJGPP project and to Novell NetWare.

The Script

#! /bin/bash
# Removes spaces in filenames (replaces them with underscore)
# Thu, 18 Oct 2007 21:34:45 -0400
for file in *;
  echo Converting "$file" to "${file// /_}"
  mv "$file" "${file// /_}"

2 Replies to “BASH – Replace Space In Filenames With Underscore”

  1. thanks! this was just what i was looking for! however i did notice that it can throw errors sometimes if something in the directory does not have a space in it’s name. here is my suggestion

    #! /bin/bash
    for file in *;
    if [[ “$file” != “${file// /_}” ]]
    echo Converting “$file” to “${file// /_}”
    mv “$file” “${file// /_}”

    this checks to make sure there would be change in name and skips if the name would be the same. this was tested in Ubuntu 9.10.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.