2
2
# replace string1 to string2 in multiple files.
3
3
# usage ./replace_string_multi_files.sh string1 string2
4
4
5
- # to avoid we miss arguments.
6
- if [ " $1 " = " " ] || [ " $2 " = " " ]; then
7
- echo " we need 2 arguments"
8
- exit
5
+ # when user doesn't input arguments, we should prompt message
6
+ # for user to input the old and new string.
7
+ if [ " $# " = " 2" ] ; then
8
+ old_string=$1
9
+ new_string=$2
10
+
11
+ else
12
+
13
+ printf " (1)replace text or (2)redo previous action? (1/2) "
14
+ read -r ans
15
+
16
+ if [ " $ans " = " 1" ]; then
17
+ printf ' Enter old string : '
18
+ read -r old_string
19
+
20
+ printf ' Enter new string : '
21
+ read -r new_string
22
+ elif [ " $ans " = " 2" ]; then
23
+
24
+
25
+ while read -r fileName; do
26
+
27
+ echo " apply redo for ${fileName} "
28
+
29
+ # apply patches
30
+ patch < .${fileName} .patch 1> /dev/null;
31
+
32
+ rm .${fileName} .patch
33
+
34
+ done < .fileList.txt
35
+
36
+ exit
37
+ fi
9
38
fi
10
39
40
+
41
+
42
+
11
43
# we also avoid to change this script.
12
44
thisScript=$0
13
45
thisScript=${thisScript# " ./" }
14
46
15
47
# to show which file in the current location has the string1 in it.
16
- echo " we have $1 in the following file"
48
+ echo " we have $old_string in the following file(s) "
17
49
echo " _______________________________"
18
- grep -r " $1 " * --color --exclude=$thisScript
50
+ grep -r " $old_string " * --color --exclude=$thisScript
19
51
echo " _______________________________"
20
- echo " replace $1 to $2 ? (y/n)"
52
+ echo " replace $old_string to $new_string ? (y/n)"
21
53
read ans
22
54
23
55
# ########################################
@@ -26,19 +58,28 @@ if [ "$ans" = "y" ];
26
58
then
27
59
28
60
# redirect filenames to a temp file.
29
- grep -lr " $1 " * --exclude=$thisScript > .fileList.txt
61
+ grep -lr " $old_string " * --exclude=$thisScript > .fileList.txt
30
62
31
63
# read in each line and assign it to fileName
32
64
# and then we do the substitution.
33
65
while read -r fileName; do
66
+
67
+ cp $fileName ${fileName} .orig
34
68
35
- echo " edited $fileName "
69
+ echo " edited $fileName "
36
70
37
- sed -i ' s|' " $1 " ' |' " $2 " ' |g' " ${fileName} "
71
+ sed -i ' s|' " $old_string " ' |' " $new_string " ' |g' " ${fileName} "
72
+
73
+ # make patches for backup.
74
+ diff -u $fileName ${fileName} .orig > .${fileName} .patch
75
+
76
+ # now we are save to remove .orig file
77
+ rm ${fileName} .orig
38
78
39
79
done < .fileList.txt
40
80
41
- rm .fileList.txt
81
+ # rm .fileList.txt
42
82
fi
43
83
44
84
85
+
0 commit comments