]> git.ipfire.org Git - thirdparty/util-linux.git/blame - misc-utils/rename.c
misc-utils: use new xmalloc() wrapper
[thirdparty/util-linux.git] / misc-utils / rename.c
CommitLineData
eb63b9b8
KZ
1/*
2 * rename.c - aeb 2000-01-01
3 *
4--------------------------------------------------------------
5#!/bin/sh
6if [ $# -le 2 ]; then echo call: rename from to files; exit; fi
7FROM="$1"
8TO="$2"
9shift
10shift
11for i in $@; do N=`echo "$i" | sed "s/$FROM/$TO/g"`; mv "$i" "$N"; done
12--------------------------------------------------------------
13 * This shell script will do renames of files, but may fail
14 * in cases involving special characters. Here a C version.
15 */
16#include <stdio.h>
17#include <string.h>
18#include <stdlib.h>
19#include <errno.h>
87f3feac 20
eb63b9b8 21#include "nls.h"
87f3feac 22#include "xalloc.h"
eb63b9b8
KZ
23
24static char *progname;
25
22853e4a 26static int
eb63b9b8
KZ
27do_rename(char *from, char *to, char *s) {
28 char *newname, *where, *p, *q;
29 int flen, tlen, slen;
30
31 where = strstr(s, from);
32 if (where == NULL)
33 return 0;
34
35 flen = strlen(from);
36 tlen = strlen(to);
37 slen = strlen(s);
87f3feac 38 newname = xmalloc(tlen+slen+1);
eb63b9b8
KZ
39
40 p = s;
41 q = newname;
42 while (p < where)
43 *q++ = *p++;
44 p = to;
45 while (*p)
46 *q++ = *p++;
47 p = where+flen;
48 while (*p)
49 *q++ = *p++;
22853e4a 50 *q = 0;
eb63b9b8
KZ
51
52 if (rename(s, newname) != 0) {
53 int errsv = errno;
54 fprintf(stderr, _("%s: renaming %s to %s failed: %s\n"),
55 progname, s, newname, strerror(errsv));
56 exit(1);
57 }
58
59 return 1;
60}
61
62int
63main(int argc, char **argv) {
64 char *from, *to, *p;
14608fdf 65 int i;
eb63b9b8
KZ
66
67 progname = argv[0];
68 if ((p = strrchr(progname, '/')) != NULL)
69 progname = p+1;
70
71 setlocale(LC_ALL, "");
72 bindtextdomain(PACKAGE, LOCALEDIR);
73 textdomain(PACKAGE);
74
75 if (argc == 2) {
76 if (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) {
baf39af1
KZ
77 printf(_("%s (%s)\n"),
78 progname, PACKAGE_STRING);
eb63b9b8
KZ
79 return 0;
80 }
81 }
82
83 if (argc < 3) {
84 fprintf(stderr, _("call: %s from to files...\n"), progname);
85 exit(1);
86 }
87
88 from = argv[1];
89 to = argv[2];
90
eb63b9b8 91 for (i=3; i<argc; i++)
14608fdf 92 do_rename(from, to, argv[i]);
eb63b9b8
KZ
93 return 0;
94}