Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Thomashighbaugh
Created October 1, 2022 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thomashighbaugh/de8735df44f9e4b814bbf753562f8f57 to your computer and use it in GitHub Desktop.
Save Thomashighbaugh/de8735df44f9e4b814bbf753562f8f57 to your computer and use it in GitHub Desktop.
A fully annotated script to remove spaces in file names that provides a thorough description of each portion of the script, describes the reasons for wanting to remove spaces and uses comment bars to create sections for the benefit of those learning BASH shell scripting and my own later reference.
#!/bin/bash
#####################################################################
# Author: Thomas Leon Highbaugh #
# #
# Description: A script to replace spaces in file names with #
# underscores to ease terminal access and navigation #
# on Unix based systems. #
# #
# For those new to Unix-like shell scripts, and my #
# own later reference, I have fully annnotated the #
# script with descriptions of all of its parts and #
# used comment bars to separate its sections. #
# #
# Purpose: In Unix-like shell environments, spaces separate #
# the various portions of a command, its parameters, #
# input,etc. So if not preceded by "\" which is the #
# escape character, the shell would think a file #
# named "Foo Bar.pdf" is two files: "Foo" and #
# "Bar.pdf". #
# #
# This can make administration of files and moving #
# around directories troublesome, especially if this #
# is being done with another script or lots of files. #
# Thus we remove the spaces, replacing it with an #
# underscore (though feel free to use whatever) to #
# prevent this problem from arising unexpectedly. #
# #
# Dependencies: On most modern Unix-like systems, this should work #
# out of the box, as it is using BASH options and #
# utilities included by default with the shell. #
# #
#####################################################################
#----------------------------------------------------------------#
# This enables the globstar option that makes the script recursive
shopt -s globstar
#----------------------------------------------------------------#
# This loop looks for files that have spaces in their names
for file in **/*\ *
do
#----------------------------------------------------------------#
# This is the command that renames the file matching the looping
# condition, replacing the space with an underscore.
mv "$file" "${file// /_}"
done
#----------------------------------------------------------------#
# End of File
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment