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
|
/*
* rename.c - aeb 2000-01-01
*
--------------------------------------------------------------
#!/bin/sh
if [ $# -le 2 ]; then echo call: rename from to files; exit; fi
FROM="$1"
TO="$2"
shift
shift
for i in $@; do N=`echo "$i" | sed "s/$FROM/$TO/g"`; mv "$i" "$N"; done
--------------------------------------------------------------
* This shell script will do renames of files, but may fail
* in cases involving special characters. Here a C version.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <getopt.h>
#include "nls.h"
#include "xalloc.h"
#include "c.h"
static int do_rename(char *from, char *to, char *s, int verbose)
{
char *newname, *where, *p, *q;
int flen, tlen, slen;
where = strstr(s, from);
if (where == NULL)
return 0;
flen = strlen(from);
tlen = strlen(to);
slen = strlen(s);
newname = xmalloc(tlen + slen + 1);
p = s;
q = newname;
while (p < where)
*q++ = *p++;
p = to;
while (*p)
*q++ = *p++;
p = where + flen;
while (*p)
*q++ = *p++;
*q = 0;
if (rename(s, newname) != 0)
err(EXIT_FAILURE, _("renaming %s to %s failed"),
s, newname);
if (verbose)
printf("`%s' -> `%s'\n", s, newname);
free(newname);
return 1;
}
static void __attribute__ ((__noreturn__)) usage(FILE * out)
{
fprintf(out,
_("Usage: %s [options] expression replacement file...\n"),
program_invocation_short_name);
fprintf(out, _("\nOptions:\n"
" -v, --verbose explain what is being done\n"
" -V, --version output version information and exit\n"
" -h, --help display this help and exit\n\n"));
exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
char *from, *to;
int i, c, verbose = 0;
static const struct option longopts[] = {
{"verbose", no_argument, NULL, 'v'},
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
while ((c = getopt_long(argc, argv, "vVh", longopts, NULL)) != -1)
switch (c) {
case 'v':
verbose = 1;
break;
case 'V':
printf(_("%s from %s\n"),
program_invocation_short_name,
PACKAGE_STRING);
return EXIT_SUCCESS;
case 'h':
usage(stdout);
default:
usage(stderr);
}
argc -= optind;
argv += optind;
if (argc < 3) {
warnx("not enough arguments");
usage(stderr);
}
from = argv[0];
to = argv[1];
for (i = 2; i < argc; i++)
do_rename(from, to, argv[i], verbose);
return EXIT_SUCCESS;
}
|