-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgres
executable file
·336 lines (315 loc) · 14.9 KB
/
gres
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/bin/sh
######################################################################
#
# GRES - "Global Regular Expression and Substitute"
#
# USAGE: gres [options] regexp replacement [file#1 [file#2 [...]]]
# ARGS : regexp, replacement
# These are the 1st and 2nd arguments on s/1/2/g.
# Available meta-chrs. set as regular expression are
# Basic Regular Expression, you can see on sed manual.
# However, you do not have to escape "/" in the strings.
# file#n
# A file to open ("-" means STDIN)
# OPTS : -E, --extended-regexp
# Regard the arguments "regexp" as extended regular expression
# (ERE) instead of a basic one (BRE). But you cannot use the
# option when an ERE supported sed command unavailable.
# -F, --fixed-strings (compatible with the same options of grep)
# Regard both arguments ("regexp", "replacement") as
# not regexp strings but simple string
# -R, -r, --recursive (compatible with the same options of grep)
# Read all files under each directory, recursively
# -- Finish recognizing the following arguments as options
#
# === Example ===
# 1. Substitute all places of the word "typo" with "type" in the files on
# the current dir.
# $ gres 'typo' 'type' *
#
# 2. Substitute the date written in comment into today (2018-02-25) in
# all of the files which has modified within 24 hours in "src" directory
# recursively.
# $ find './src' -type f -mtime -1 |
# > xargs gres '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}' '2018-02-25'
#
# 3. I want to replace all places of string "-R" into "-r", but the strings of
# which start by "-" will be misunderstood as an option. How should I type
# for?
# $ gres -- '-R' '-r' *
#
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2021-03-21
#
# This is a public-domain software (CC0). It means that all of the
# people can use this for any purposes with no restrictions at all.
# By the way, We are fed up with the side effects which are brought
# about by the major licenses.
#
# The latest version is distributed at the following page.
# https://github.com/ShellShoccar-jpn/misc-tools
#
######################################################################
######################################################################
# Initial Configuration
######################################################################
# === Initialize shell environment ===================================
set -u
umask 0022
export LC_ALL=C
export PATH="$(command -p getconf PATH 2>/dev/null)${PATH+:}${PATH-}"
case $PATH in :*) PATH=${PATH#?};; esac
export UNIX_STD=2003 # to make HP-UX conform to POSIX
# === Define the functions for printing usage and error message ======
print_usage_and_exit () {
cat <<-USAGE 1>&2
Usage : ${0##*/} [options] regexp replacement [file#1 [file#2 [...]]]
Args : regexp(BRE), replacement
These are the 1st and 2nd arguments of s/1/2/g.
Available meta-chr. set as regular expression is
Basic Regular Expression, you can see on sed manual.
However, you do not have to escape "/" in the strings.
file#n
A file to open ("-" means STDIN)
Options : -E, --extended-regexp
Regard the arguments "regexp" as extended regular expression
(ERE) instead of a basic one (BRE). But you cannot use the
option when an ERE supported sed command unavailable.
-F, --fixed-strings (compatible with the same options of grep)
Regard both arguments ("regexp", "replacement") as
not regexp strings but simple string
-R, -r, --recursive (compatible with the same options of grep)
Read all files under each directory, recursively
-- Finish recognizing the following arguments as options
Version : 2021-03-21 23:50:18 JST
(POSIX Bourne Shell/POSIX commands)
USAGE
exit 1
}
error_exit() {
${2+:} false && echo "${0##*/}: $2" 1>&2
exit $1
}
# === Define misc variables ==========================================
LF=$(printf '\n_');LF=${LF%_} # <0x0a>
######################################################################
# Argument Parsing
######################################################################
# === Set default values =============================================
optF=0
optE=0
optR=0
optHH=''
case "${0##*/}" in 'egres') optE=1;; 'fgres') optF=1;; esac
# === Parse arguments (except files) =================================
optmode=''
while :; do
case $# in 0) break;; esac
case "$optmode" in
'') case "$1" in
-) case $# in 1) break;; esac
;;
-[EFRr]*)
s=$(printf '%s\n' "${1#-}" |
awk '{opt = "_"; err=""; #
l = length($0); #
for (n=1;n<=l;n++) { #
c = substr($0, n, 1); #
if (c=="E") { opt = opt "E"; } #
else if (c=="F") { opt = opt "F"; } #
else if (c=="R") { opt = opt "R"; } #
else if (c=="r") { opt = opt "R"; } #
#else if (c=="X") { opt = opt "X";break;} #
else { err = "!"; } #
} #
arg = (n<l) ? substr($0,n+1) : ""; #
printf("%s%s %s",err,opt,arg); }')
arg=${s#* }
s=${s%% *}
case "$s" in '!'*) print_usage_and_exit;; esac
case "$s" in *E*) optE=1 ;; esac
case "$s" in *F*) optF=1 ;; esac
case "$s" in *p*) optp=1 ;; esac
case "$s" in *R*) optR=1 ;; esac
case "$s" in *t*) optt=1 ;; esac
#case "$s" in *X*) optmode='X' ;; esac
shift;
case "$arg" in '') continue;; esac
;;
--recursive)
optR=1
shift
continue
;;
--extended-regexp)
optE=1
shift
continue
;;
--fixed-strings)
optF=1;
shift
continue
;;
#--dummy=*)
# optx=${s#--dummy=}
# shift
# continue
# ;;
--) optHH='--'
shift
break
;;
-*) print_usage_and_exit
;;
*) break
;;
esac
;;
*) arg=$1
shift
;;
esac
case "$optmode" in
#X) optX=$arg ;;
*) error_exit 1 'There is a BUG is in this program';;
esac
optmode=''
done
case "$#" in
[01]) print_usage_and_exit ;;
*) pat=$1; sub=$2; shift 2;;
*)
esac
case "$#" in 0) set -- -;; esac
case "$optR/$#/$1" in '1/1/-')
error_exit 1 'You cannot use recursive option (-R,-r,--recursive) for STDIN'
;; esac
# === Validate options ===============================================
case "$optE$optF" in 11)
error_exit 1 'conflicting matchers specified';;
esac
case "$pat" in *"$LF"*)
error_exit 1 '<0x0A> in "regexp" argument is not allowed';;
esac
######################################################################
# Prepare for the Main Routine
######################################################################
# === Decide the option string for sed ===============================
opt4sed=''
CMDSED='sed'
case $optE in 0) :;; *)
if [ $(echo ABC | sed -E 's/.+/OK/' 2>/dev/null) = 'OK' ]; then
opt4sed='-E'
elif [ $(echo ABC | sed -r 's/.+/OK/' 2>/dev/null) = 'OK' ]; then
opt4sed='-r'
elif [ $(echo ABC | gsed -r 's/.+/OK/' 2>/dev/null) = 'OK' ]; then
opt4sed='-r's
CMDSED='gsed'
else
error_exit 1 'No ERE supported sed is found. You cannot use -E option.'
fi
;;
esac
# === Decide the strings for grep and sed ============================
case $optF in
0) pat4sed=$(printf '%s\n' "$pat" |
# --- escape all of "/" ------------------------------------- #
awk ' #
BEGIN{ #
# --- 0) initialize #
OFS=""; #
ORS=""; #
iBra=0; # ==0 : out of a bracket #
# ==1 : on entering a bracket #
# >=1 : during in a bracket #
fEsc=0; # >0 : to have to escape the next character #
fPcc=0; # >0 : possibility of the top of POSIX charclass #
# --- 1) start of line loop #
while (getline line) { #
# #
# --- 2) start of character-loop #
l=length(line); #
for (i=1; i<=l; i++) { #
# #
# --- 3) get a character (or POSIX charclass) #
if (fPcc==0) { #
s=substr(line,i,1); #
} else { #
s1=substr(line,i); #
if (match(s1,/^:[a-z]+:\]/)) { #
s=substr(s1,1,RLENGTH); #
i=i+RLENGTH-1; #
} else { #
s=substr(s1,1, 1); #
} #
fPcc=0; #
} #
# #
# --- 4) Escape "/" if required #
if ( iBra==0) { #
if (fEsc >0) {print s ; fEsc=0; continue;} #
if (s=="\\") {print "\\" ; fEsc=1; } #
else if (s=="[" ) {print "[" ; iBra=1; } #
else if (s=="/" ) {print "\\/"; } #
else {print s ; } #
} else if (iBra==1) { #
if (s=="^" ) {print "^" ; } #
else if (s=="[" ) {print "[" ; iBra=2; fPcc=1; } #
else {print s ; iBra=2; } #
} else { #
if (s=="[" ) {print "[" ; fPcc=1; } #
else if (s=="]" ) {print "]" ; iBra=0; } #
else {print s ; } #
} #
# #
# --- 5) end of character-loop #
} #
# #
# --- 6) end of line-loop #
print "\n"; #
} #
}' )
sub4sed=$(printf '%s\n' "${sub}_" |
# --- escape all of "/" #
sed 's/\//\\\//g' )
sub4sed=${sub4sed%_}
;;
*) pat4sed=$(printf '%s\n' "$pat" |
# --- escape all of BRE meta chrs.#
sed 's/\([].\*/[]\)/\\\1/g' |
sed '1s/^^/\\^/' |
sed '$s/$$/\\$/' )
sub4sed=$(printf '%s\n' "${sub}_" |
# --- escape all of BRE meta chrs.#
sed 's/\([\&/]\)/\\\1/g' |
sed 's/$/\\/' |
sed '$s/\\$//' )
sub4sed=${sub4sed%_}
;;
esac
######################################################################
# Main Routine
######################################################################
case "$optR" in
0) (cat ${1+"$@"}; echo '') |
"$CMDSED" $opt4sed "s/$pat4sed/$sub4sed/g" |
awk 'BEGIN{ORS=""; OFS=""; #
getline line; #
print line; #
dlm=sprintf("\n"); #
while (getline line) {print dlm,line;} }';;
*) find "$@" -type f |
xargs cat |
(cat; echo '') |
"$CMDSED" $opt4sed "s/$pat4sed/$sub4sed/g" |
awk 'BEGIN{ORS=""; OFS=""; #
getline line; #
print line; #
dlm=sprintf("\n"); #
while (getline line) {print dlm,line;} }';;
esac
######################################################################
# Finish
######################################################################
exit 0