Removing/renaming multiple files containing spaces is a bit difficult task.  for, while loop, mv, cp commands can not understand spaces, we have to use  for mentioning spaces some of the commands.

For example if we take “for loop” to convert all the files in a given directory we will face issue, because for loop will take space as a separator between given entries

for i in *
do
VAR1=$(echo “$i” | sed ‘s/ /_/g’)
mv “$i” “$VAR1”
done

The problem here is that
1)for look can not understand spaces
2)mv command do not understand spaces

Suppose I have a file name as “abc read.txt”, but this commands will take as abc and read.txt as two files which is not right. one way to make mv, cp command to understand space is using ” “. But for loop still don’t have this feature.

One solution is to use rename command which supports Regexp, Batch remaining files etc.

Check if rename command, if it’s not installed install it.

In Debian based machines:

apt-get install rename

In Red hat based machines:

yum install rename

Once the command is installed go to the directory where you have files with spaces in it and execute below any command

rename ‘s/ /_/g’ *
or
rename ‘ ‘ ‘_’ *

This is an excellent command which have inbuilt capabilities of Regexp, tr command, sed command etc.

Shell script to rename files in multiple directories which are in a parent directory

#!/bin/bash
for i in *
do
rename ‘s/ /_/g’ $i/*
done



if your directories falls under different folders then get that links in to a file and use below for loop for that


#!/bin/bash
for i in $(cat /path/to/dir.txt)
do
rename 's/ /_/g' $i/*
done

These two scripts will help us in reduce time.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.