-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodify
executable file
·133 lines (114 loc) · 2.49 KB
/
modify
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/bin/sh
# script modify for EOPSY laboratory 1
# author: Kacper Wojakowski 293064
name=`basename $0`
# function for printing out errors
print_error()
{
echo "$name: error: $1" 1>&2
}
# test if there is an option already
test_sedp()
{
if [ $1 != "n" ]
then
print_error "only one option from -l, -u, <sed pattern> is allowed at a time"; exit 1;
fi
}
# recursive function
recursive()
{
for el in "$1"/*
do
oldname=`basename $el`
# If there are no files in the directory, finish
if [ "$oldname" = "*" ]
then
break
fi
newname="$1/`echo $oldname | sed $2`"
# Only rename if the name was changed
if [ "$newname" != "$oldname" ]
then
mv "$el" "$newname"
fi
# If it is a directory, go inside
if [ -d "$newname" ]
then
recursive "$newname" "$2"
fi
done
}
# when no arguments or -h chosen, print help and exit
if [ -z "$1" ] || [ "$1" = "-h" ]
then
cat<<EOT
$name is a script which modifies filenames, lowercasing/uppercasing them, or calling the given sed pattern
usage:
$name [-h]
$name [-r] [-l|-u] <dir/file names...>
$name [-r] <sed pattern> <dir/file names...>
options:
-h shows help
-r turns on recursion
-l|-u chooses between lowercase and uppercase
<sed pattern> sed patter with which to modify the names instead of lower/uppercasing
if neither -l or -u is chosen, the first non-option argument is taken as the sed pattern
$name correct syntax examples:
$name -l file1 file2
$name -r -u directory
$name 's/x/Y/' xylophone.txt file_xyz xxdir
$name incorrect syntax examples:
$name -d
$name -u -l file
$name -r -u
EOT
exit 0
fi
# choosing options from arguments
r=n
sedp=n
while [ "x$1" != "x" ]
do
case "$1" in
-r) r=y;;
-l) test_sedp "$sedp"; sedp='s/[A-Z]/\L&/g';;
-u) test_sedp "$sedp"; sedp='s/[a-z]/\U&/g';;
-*) print_error "wrong option $1"; exit 1;;
*) if [ $sedp = "n" ]
then
sedp="$1"
else
break
fi;;
esac
shift
done
# testing empty sed pattern
if [ $sedp = "n" ]
then
print_error "no option chosen: choose one from -l, -u, <sed pattern>"
exit 1
fi
# testing empty file/directory list
if [ -z "$1" ]
then
print_error "no file or directory names given"
exit 1
fi
# Changing filenames
while [ "x$1" != "x" ]
do
newname="`echo $1 | sed $sedp`"
# Only rename if name has changed
if [ "$newname" != "$1" ]
then
mv "$1" "$newname"
fi
# if recursion is on and argument is a directory
if [ $r = "y" ] && [ -d $newname ]
then
recursive "$newname" "$sedp"
fi
shift
done