forked from ArthurGareginyan/space_to_underscore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspace_to_underscore.sh
90 lines (78 loc) · 2.84 KB
/
space_to_underscore.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/bash
#=============================================================#
# Name: Space to Underscore #
# Description: Recursively replace spaces with underscores #
# in file and directory names. #
# Version: ver 1.2 #
# Data: 16.6.2014 #
# Author: Arthur Gareginyan #
# Author URI: https://www.arthurgareginyan.com #
# Email: [email protected] #
# License: GNU General Public License, version 3 (GPLv3) #
# License URI: http://www.gnu.org/licenses/gpl-3.0.html #
#=============================================================#
# USAGE:
# chmod +x space_to_underscore.sh
# cd /home/user/example
# ~/space_to_underscore.sh "find_this" "replace_with_this"
# Check for proper priveliges
[ "`whoami`" = root ] || exec sudo "$0" "$@"
####################### DIALOG ############################
echo -en "\n BEWARE! Starting from current directory (`pwd`),"
echo -en " files and directories with spaces in name will be renamed automatically.\n"
echo -en "\n Press \"ENTER\" to continue or \"N\" to exit:"
read ops
case "$ops" in
n|N)
echo -en "\n Canceled by User. Exiting...\n"
exit 1 ;;
*)
echo -en "\n Begining...\n" ;;
esac
################### SETUP VARIABLES #######################
number=0 # Number of renamed.
number_not=0 # Number of not renamed.
IFS=$'\n'
array=( `find ./ -type d` ) # Find catalogs recursively.
######################## GO ###############################
# Reverse cycle.
for (( i = ${#array[@]}; i; )); do
# Go in to catalog.
pushd "${array[--i]}" >/dev/null 2>&1
# Search of all files in the current directory.
for name in *
do
# Check for spaces in names of files and directories.
echo "$name" | grep -q "$1"
if [ $? -eq 0 ]
then
# Replacing spaces with underscores.
newname=`echo $name | sed -e "s/$1/$2/g"`
if [ -e $newname ]
then
let "number_not +=1"
echo " Not renaming: $name"
else
# Plus one to number.
let "number += 1"
# Message about rename.
echo "$number Renaming: ${array[i]}/$name"
# Rename.
mv "$name" "$newname"
fi
fi
done
# Go back.
popd >/dev/null 2>&1
done
echo -en "\n All operations is complited."
if [ "$number_not" -ne "0" ]
then echo -en "\n $number_not not renamed."
fi
if [ "$number" -eq "0" ]
then echo -en "\n Nothing been renamed.\n"
elif [ "$number" -eq "1" ]
then echo -en "\n $number renamed.\n"
else echo -en "\n Renamed files and catalogs: $number\n"
fi
exit 0