aboutsummaryrefslogtreecommitdiff
path: root/shell/match.c
diff options
context:
space:
mode:
Diffstat (limited to 'shell/match.c')
-rw-r--r--shell/match.c141
1 files changed, 141 insertions, 0 deletions
diff --git a/shell/match.c b/shell/match.c
new file mode 100644
index 000000000..0810fd8f6
--- /dev/null
+++ b/shell/match.c
@@ -0,0 +1,141 @@
1/*
2 * ##/%% variable matching code ripped out of ash shell for code sharing
3 *
4 * Copyright (c) 1989, 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
8 * was re-ported from NetBSD and debianized.
9 *
10 * This code is derived from software contributed to Berkeley by
11 * Kenneth Almquist.
12 *
13 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14 *
15 * Original BSD copyright notice is retained at the end of this file.
16 */
17
18#ifdef STANDALONE
19# include <stdbool.h>
20# include <stdio.h>
21# include <stdlib.h>
22# include <string.h>
23# include <unistd.h>
24#else
25# include "busybox.h"
26#endif
27#include <fnmatch.h>
28#include "match.h"
29
30#define pmatch(a, b) !fnmatch((a), (b), 0)
31
32char *scanleft(char *string, char *pattern, bool zero)
33{
34 char c;
35 char *loc = string;
36
37 do {
38 int match;
39 const char *s;
40
41 c = *loc;
42 if (zero) {
43 *loc = '\0';
44 s = string;
45 } else
46 s = loc;
47 match = pmatch(pattern, s);
48 *loc = c;
49
50 if (match)
51 return loc;
52
53 loc++;
54 } while (c);
55
56 return NULL;
57}
58
59char *scanright(char *string, char *pattern, bool zero)
60{
61 char c;
62 char *loc = string + strlen(string);
63
64 while (loc >= string) {
65 int match;
66 const char *s;
67
68 c = *loc;
69 if (zero) {
70 *loc = '\0';
71 s = string;
72 } else
73 s = loc;
74 match = pmatch(pattern, s);
75 *loc = c;
76
77 if (match)
78 return loc;
79
80 loc--;
81 }
82
83 return NULL;
84}
85
86#ifdef STANDALONE
87int main(int argc, char *argv[])
88{
89 char *string;
90 char *op;
91 char *pattern;
92 bool zero;
93 char *loc;
94
95 int i;
96
97 if (argc == 1) {
98 puts(
99 "Usage: match <test> [test...]\n\n"
100 "Where a <test> is the form: <string><op><match>\n"
101 "This is to test the shell ${var#val} expression type.\n\n"
102 "e.g. `match 'abc#a*'` -> bc"
103 );
104 return 1;
105 }
106
107 for (i = 1; i < argc; ++i) {
108 size_t off;
109 scan_t scan;
110
111 printf("'%s': ", argv[i]);
112
113 string = strdup(argv[i]);
114 off = strcspn(string, "#%");
115 if (!off) {
116 printf("invalid format\n");
117 free(string);
118 continue;
119 }
120 op = string + off;
121 scan = pick_scan(op[0], op[1], &zero);
122 pattern = op + 1;
123 if (op[0] == op[1])
124 op[1] = '\0', ++pattern;
125 op[0] = '\0';
126
127 loc = scan(string, pattern, zero);
128
129 if (zero) {
130 printf("'%s'\n", loc);
131 } else {
132 *loc = '\0';
133 printf("'%s'\n", string);
134 }
135
136 free(string);
137 }
138
139 return 0;
140}
141#endif