-
Notifications
You must be signed in to change notification settings - Fork 1
/
strswap
executable file
·76 lines (64 loc) · 1.7 KB
/
strswap
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
#!/usr/bin/env bash
help()
{
cat <<END
Synopsis:
Swap all occurences of old string with new string in files.
Usage:
$USAGE
Description:
Replace all occurences of old string with new string in a text file.
The overwriting of the new file is handled by the overwrite script.
Unfortunately, neither the source nor target strings can contain
regular expression meta characters used by sed, since the
escaping algorithm in strswap is incorrect.
This script is derived from an example in the mighty fine book
title "The Unix Programming Environment" by Rob Pike and Brian
Kernighan.
Depends:
GNU or BSD sed command
https://github.com/jmscott/work/overwrite
See:
https://github.com/jmscott/work/strswap
http://www.amazon.com/Unix-Programming-Environment-Prentice-Hall-Software/dp/013937681X
Note:
A --verbose or -v option would be nice.
The meta escaping of sed command needs a rethink.
A --word option would be nice.
END
}
PROG=$(basename $0)
USAGE="$PROG old_string new_string file1 [file2 ...]"
die()
{
echo "$PROG: ERROR: $@" >&2
echo "usage: $USAGE" >&2
exit 1
}
#
# Synopsis:
# Half assed attempt to escape sed regular expression meta characters.
#
escape_sed_meta()
{
echo "$1" |
sed "s/'/\\'/g" |
sed 's/[\]/[\]/g' |
sed 's/\//\\\//g' |
sed 's/\./\\./g' |
sed 's/\*/\\*/g'
}
test $# -lt 3 && die "wrong number of arguments: $#"
#
# Escape the strings.
# This algorithm is not correct, since not all sed meta characters
# are escaped.
#
OLD_STRING="$(escape_sed_meta "$1")"
NEW_STRING="$(escape_sed_meta "$2")"
SED_COMMAND='s/'$OLD_STRING'/'$NEW_STRING'/g'
echo "SED_COMMAND=$SED_COMMAND"
shift; shift
for FILE; do
sed "$SED_COMMAND" $FILE | overwrite $FILE
done