Skip to content

Commit 3c8f657

Browse files
authored
updates
1 parent fcfdad1 commit 3c8f657

File tree

1 file changed

+52
-11
lines changed

1 file changed

+52
-11
lines changed

replace_string_multi_files.sh

+52-11
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,54 @@
22
# replace string1 to string2 in multiple files.
33
# usage ./replace_string_multi_files.sh string1 string2
44

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
938
fi
1039

40+
41+
42+
1143
# we also avoid to change this script.
1244
thisScript=$0
1345
thisScript=${thisScript#"./"}
1446

1547
# 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)"
1749
echo "_______________________________"
18-
grep -r "$1" * --color --exclude=$thisScript
50+
grep -r "$old_string" * --color --exclude=$thisScript
1951
echo "_______________________________"
20-
echo "replace $1 to $2? (y/n)"
52+
echo "replace $old_string to $new_string? (y/n)"
2153
read ans
2254

2355
#########################################
@@ -26,19 +58,28 @@ if [ "$ans" = "y" ];
2658
then
2759

2860
# redirect filenames to a temp file.
29-
grep -lr "$1" * --exclude=$thisScript > .fileList.txt
61+
grep -lr "$old_string" * --exclude=$thisScript > .fileList.txt
3062

3163
# read in each line and assign it to fileName
3264
# and then we do the substitution.
3365
while read -r fileName; do
66+
67+
cp $fileName ${fileName}.orig
3468

35-
echo "edited $fileName"
69+
echo "edited $fileName"
3670

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
3878

3979
done < .fileList.txt
4080

41-
rm .fileList.txt
81+
# rm .fileList.txt
4282
fi
4383

4484

85+

0 commit comments

Comments
 (0)