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/bashfor i in $(cat /path/to/dir.txt)dorename 's/ /_/g' $i/*doneThese 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)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018