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 *
VAR1=$(echo “$i” | sed ‘s/ /_/g’)
mv “$i” “$VAR1”
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’ *
rename ‘ ‘ ‘_’ *
Shell script to rename files in multiple directories which are in a parent directory
for i in *
rename ‘s/ /_/g’ $i/*
if your directories falls under different folders then get that links in to a file and use below for loop for that
#!/bin/bashfor i in $(cat /path/to/dir.txt)dorename '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.
Latest posts by Surendra Anne (see all)
- Online training on Linux Bash shell scripting - February 8, 2018
- 15 iostat command examples in Linux/Unix - December 4, 2017
- How to Installing and Configuring Firewalld on Linux - November 29, 2017
- 4 sleep command examples in Linux/Unix - November 2, 2017
- 5 SSH alias examples in Linux - October 16, 2017