-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenameFiles
More file actions
executable file
·2069 lines (1692 loc) · 68.4 KB
/
renameFiles
File metadata and controls
executable file
·2069 lines (1692 loc) · 68.4 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl -w
#
# renamefiles: Absurdly flexible bulk file-renaming.
# Written 2006-12-18 by Steven J. DeRose.
#
use strict;
use Getopt::Long;
use Encode;
use POSIX qw(strftime);
use sjdUtils;
use alogging;
our %metadata = (
"title" => "renameFiles",
"description" => "Absurdly flexible bulk file-renaming.",
"rightsHolder" => "Steven J. DeRose",
"creator" => "http://viaf.org/viaf/50334488",
"type" => "http://purl.org/dc/dcmitype/Software",
"language" => "Perl 5.18",
"created" => "2006-12-18",
"modified" => "2024-06-05",
"publisher" => "http://github.com/sderose",
"license" => "https://creativecommons.org/licenses/by-sa/3.0/"
);
our $VERSION_DATE = $metadata{"modified"};
=pod
=head1 Usage
renameFiles [options] [regex] [files]
Apply a regular expression, or any of a range of built-in operations,
to rename a file(s). Can do systematic changes such as (see below for more):
* imposing or removing camel or other case patterns,
* normalizing date strings,
* moving date strings to the front for sortability,
* getting rid of unwelcome characters (even by file-system type)
* padding sequence numbers,
* inserting the values of various file attributes
(date, owner id, or even the source URI when available) into the name.
For files under git control, set I<--gitMoves> to check status
and attempt "git mv" instead of a regular rename when applicable.
=head2 Examples
A commonly useful case is to turn all characters not in C<[-.\\w]> into "_":
renameFiles --clean *
The same thing via an equivalent (Perl-style) regular expression change:
renamefiles --expr "s/[^-.\\w]/_/g" *.htm
To pad numbers to a uniform number of digits (in this case 4):
renamefiles --expr 's/^(\d+)/\$1/'"' --ePad 4 *.htm
Be sure to backslash or quote '$' (such as when used for back-references
as in this example).
Renames all .htm files in the current directory whose names contain
"myFile", "myStuff", or "myData" to refer to "Herodotuses" in place of the "my".
renamefiles --expr "s/my(File|Stuff|Data)/Herodotuses_\$1/" *.htm
B<Note>: Changes apply to each filename, not the path leading to it,
nor to an extension (unless you set certain options).
They do apply to names of directories, unless you set I<--no-dirs>).
There are options to:
=over
=item * normalize dates or numbers in names, and/or move them to the front
(I<--dates>, I<--epad>, etc.),
=item * modify character-set and case usage (I<--camelize>, I<--clean>, I<--lc>),
=item * convert names to conform to various file-systems
(I<--fileSystem [name]>, such as by removing or replacing prohibited characters.
Use I<--help-filesystem> to get a list of names.
=item * insert ancestor directory names into the filename (I<--pull>),
=item * insert content extracted from the file's contents (I<--pullContent>),
=item * insert names extracted from the URI from which a file was downloaded
(I<--pullURI>, MacOS only),
=item * insert serial numbers to avoid conflicts (I<--resolve>, I<--pad>),
=item * fiddle with extensions (I<--addExtension>, I<--extChanges>,
I<--onlyExtensions>, I<-x>),
=item * prepend file access, creation, or modification dates, etc. (I<--addStat>),
=item * handle conventions for naming duplicates and backups (I<--copies>),
=item * fix URI-style %XX special-character codes (I<--unescapeURI>),
=back
=head2 Order of changes
Renaming actions happen in the order (listed by option names):
copies, pull, pullURI, xattrAdd, unescapeURI, lc, uc, bactrianize,
camelize, addStat, dates, expr, clean. The easiest way to force a
different order is probably to use multiple C<renameFiles> commands.
=head1 Options
(prefix "no" to negate where applicable)
=over
=item * B<--addExtension> I<ext>
Add an extension to files that don't already have one.
Use I<ext> as the extension (don't specify the "."), except that if I<ext> is
set to "!", use the *nix C<file> command to figure out what the file is, and
provide the appropriate extension from an internal list. C<file> is not
complete, nor is the internal list. For example, a Java source file (at
least on Mac OS when I checked) comes back merely as "ASCII text",
which the list maps to extension "txt".
See also I<--extChanges>.
=item * B<--addStat> I<n>
Prefix a piece of file-system information (from C<stat>) to the filename.
For example, specify I<mtime> or I<9> to insert the modification date
of the file (see the following list).
Times are converted to dates in yyyy-mm-dd form
(time and datetime will likely be added as well).
See also I<--dates>, which can be used to normalize date formats in filenames.
The fields of I<stat> can be specified by number or by the short names here:
0 dev device number of filesystem
1 ino inode number
2 mode file mode (type and permissions)
3 nlink number of (hard) links to the file
4 uid numeric user ID of file's owner
5 gid numeric group ID of file's owner
6 rdev the device identifier (special files only)
7 size total size of file, in bytes
8 adate last access time in seconds since the epoch
9 mdate last modify time in seconds since the epoch
10 cdate inode change time in seconds since the epoch (*)
11 blksize preferred I/O size in bytes for interacting with the
file (may vary from file to file)
12 blocks actual number of system-specific blocks allocated
on disk (blocks are often, but not always, 512 bytes each)
=item * B<--ancestor>
As the first step I<when resolving name conflicts>,
prefix the name of the parent directory, plus the
I<--separator> character (default "_"), to the filename.
See also I<--pull>, I<--pullURI>, and I<--pullContent>
(which do a similar operation
regardless of whether there is any name conflict).
=item * B<--bactrianize> OR B<--camelToSpace>
Insert a space before each non-initial capital letter in names (except where
there already is such a space).
For example, "TodaysNewsHeadlines" becomes "Todays News Headlines".
B<Note>: A Bactrian camel has two humps with a gap between; this option
inserts a "gap". This does not do anything special for names like "DeRose".
See also I<--camelize>.
=item * B<--camelize>
Remove whitespace runs from names, but capitalize the character following each.
For example, "Todays news headlines" becomes "TodaysNewsHeadlines".
If you also specify I<--lc>, I<--lc> is done first.
See also I<--bactrianize>.
=item * B<--clean>
Change unusual characters to "_".
"Unusual" means characters that are not among C<[-.\\w]>.
=item * B<--copies>
Scan for various OS conventions for duplicate files, such as
"Copy 4 of foo", "foo - Copy (4)", "foo (another copy)", etc.
Where found, replace them with a trailing I<--separator>
character and number (left zero-padded if you specify I<--pad>).
If there are already numbered editions, avoid overwriting them.
However, nothing is done to ensure that the editions are numbered in
order by mod date or some other criterion.
Experimental.
=item * B<--dateOutput> I<formatString>
Change the format that dates are converted to with I<--dates>.
Takes an argument of the form expected by I<strftime()> (the code uses
strftime, and accounts for it wanting 0-based days and 1900-based years).
Default: "%Y-%m-%d", which produces the ISO 8601 date format (yyyy-mm-dd),
which sorts right, avoids ambiguity between US and UK forms, etc.
=item * B<--dates>
Notice simple dates embedded in names, change them to yyyy-mm-dd form
(see ISO 8601), and move them to the beginning of the filenames. See also I<--addStat>.
The formats recognized include:
02/28/1776 (US style (mm/dd/yyyy)
Feb. 28, 1776
28 Feb 1776
1776-02-28
1776-02 (day defaults to 1)
17760228
Feb 1776
To recognize European style (dd/mm/yyyy) instead of US, set I<--uk>.
All matches must begin and end at word boundaries (regex "\\b").
Month names are recognized spelled out in full or
abbreviated, as set for the current C<locale>. Dots, commas, and the amount and type
of whitespace can be varied. 4-digits years alone are not affected; for
that see I<--dateyears>.
=item * B<--dateyears>
This option is similar to I<--dates>, but recognizes lone 4-digit years beginning
with "1" or "2", and merely moves them to the front (a 4-digit year by itself
is a valid ISO 8601 data representation). This option will I<not> move
them if followed by a hyphen or digit.
=item * B<--dirs>
Rename directories just like anything else (defaults to be on; use
I<--no-dirs> to turn off). Compatible with, but not the same as, I<--recursive>.
There is no setting (yet) to operate I<only> on directories.
=item * B<--dot>
Include hidden files (that is, files whose names begin with ".").
=item * B<--dropExtensions>
Delete file extensions.
=item * B<--dropOriginal>
Don't include the original name in the result. For the moment, this only
applies when I<--pullContent> is used; it should be extended to other
options that similarly append brand-new, likely-unique strings to the filenames.
=item * B<--ePad> I<num>
With I<--expr>, left-pad the I<to> value to a minimum of I<num> characters.
The pad character used can be controlled via I<--ePadChar>.
This can be useful, among other things, for normalizing the length of
embedded numbers.
The padding is applied to the right hand side as a whole:
renameFiles -epad 6 -e "s/([\d+])/$1/" *.foo
This would, for example, rename F<zork37> to F<zork000037>.
See also I<--pad>, which instead affects numbers appended to avoid conflicts
while renaming.
=item * B<--ePadChar> I<c>
The character to use when padding right-hand sides with I<--ePad>. Default: "0".
With I<--expr>, left-pad the I<to> value to a minimum of I<num> characters.
=item * B<--expr> I<'s/lhs/rhs/'> OR B<-e> I<'s/lhs/rhs/'>
Apply the given regex to filenames (several examples are given near the start of
this help). All matches are changed, not just the first.
This uses PERL regexes, and respects the I<--ignorecase> option.
To use a capture, use $1 etc. on the right-hand side, not \\1.
But remember to backslash or quote the "$" to protect it from the shell.
This change does not affect filename extensions unless you
also specify I<--extChanges>.
See also I<--ignoreCase>.
This option is I<not> repeatable.
=item * B<--extChanges> OR B<--extensions>
Apply the I<--expr> change to full filenames including any file extensions,
instead of to the basenames excluding the extensions.
Experimental. See also I<--onlyExtensions>.
=item * B<--filesystem> I<name>
Ensure that all filenames conform to the requirements of a certain filesystem.
For example, MacOSX prohibits colons, Windows backslashes, and various systems
have different maximum name lenths. To see a list of supported file systems,
with their names and constraints, use I<--help-filesystems>.
B<Note>: Maximum filename lengths for different file systems may not be
measured the same. For example, both Mac and ext4 (at least on Synology)
say 255, but if the Mac name includes UTF-8 the byte count can apparently
go over 255, in which case copying to ext4 seems to fail.
=item * B<--force>
Overwrite conflicting output files with prejudice. Experimental.
This is not intended to overwrite output directories.
=item * B<--gitMoves>
Do "git mv" rather than regular mv (when applicable).
=item * B<--ignoreCase> OR I<-i>
Add the "i" option to the regex change specified by I<--expr>,
so the change ignores case distinctions.
=item * B<--xattrAdd> I<itemName>
Append to the filename, the specified item extracted from MacOS file-system
metadata for the file (when available). Such items can be accessed by the
shell command C<mdfind>, and have names beginning C<xattrItem> (that prefix may
be omitted when using this option). This option should be, but is not, repeatable.
However, you can run C<renameFiles> multiple times to add one item at a time.
The available items can be listed by using the I<--xattrList> option.
=item * B<--xattrList>
List all available items that can be specified for the I<--xattradd>.
=item * B<--lc> OR B<--lower>
Force filenames entirely to lower case.
This does not affect extensions.
=item * B<--lowerExtensions> OR B<--lcExtensions>
Force file extensions to lower case.
=item * B<--onlyExtensions>
Apply any I<--expr> changes to file extensions only (not to the
basename, nor to the full name including the extension). Do not include the ".".
Experimental. See also I<--extChanges>.
=item * B<--pad> I<num>
With I<--resolve>, left-pad the number to a minimum of I<num> digits.
In case of name conflicts, padded numbers are tried, from 0 up to 10**I<num>.
If no filename in that range is available, the rename fails.
<Note>: See also I<--ePad>, to pad the "to" side of an I<--expr> change.
=item * B<--pull> I<n>
Add the names of the I<n> nearest containing directories into the filename
proper, separated by the I<--separator> character (default "_").
See also I<--ancestor> and I<--pullURI>.
For example, with I<--pull 2> a file at
/home/jsmith/pix/pets/rover_12.jpg
becomes
/home/jsmith/pix/pets/pix_pets_rover_12.jpg
=item * B<--pullContent>
Extract content from the beginning of the file and put it into the name.
The first record is read, and any HTML or XML tags are stripped out
(for actual HTML or XML, it would typically be better to extract a title or
similar). Unusual characters are removed, spaces are changed to "_", and
the result is truncated at 40 characters, then appended to the filename.
=item * B<--pullNoEntities>
If set, then I<--pullContent> will discard not only tags, but also entity
and numeric character references.
=item * B<--pullURI> I<n>
Extract the URI from which the file was downloaded (Mac only,
obtained via the C<xattrs> command).
Then add the names of the last I<n> directories from the URI (assuming
it's a directory-style URI) into the filename proper
(see also I<--ancestor> and I<--pull>, and the C<whereFrom> command).
The directory names are separated by the I<--separator> value
(since a literal "/" would be at least inconvenient).
=item * B<--quiet> OR B<-q>
Suppress most messages.
=item * B<--recursive> OR B<-r>
Run through subdirectories, too. Experimental. See also I<--dirs>.
=item * B<--resolve>
If a rename leads to a conflict, suffix a serial-number. See also I<--pad>.
Default (unset with I<--no-resolve>).
=item * B<--separator> I<s>
Use I<s> (default "_") in place of any characters to be removed
by I<--clean>, and to separate directory names prepended to
the filename by I<--ancestor>, I<--pull>, etc.
=item * B<--test> OR B<--dry-run> OR B<--dryrun>
Run through and show what would be done, but don't actually rename anything.
B<Note>: This is not a perfect test, since actual renaming of early files
might produce conflicts later (which will not be noticed with I<--test>).
=item * B<--uc> OR B<--upper>
Force filenames entirely to upper-case.
This does not affect extensions.
=item * B<--uk>
Look for dates as dd/mm/yyyy instead of mm/dd/yyyy.
=item * B<--unescapeURI>
Expand %xx special characters (such as used in URIs).
This functionality is also available by itself, with the
separate command C<unescapeURI>.
=item * B<--unroman>
Find roman numerals within filenames and convert them to Arabic numerals
(subject also to I<--pad>).
Roman numerals are defined (too loosely) as sequences of [ivxlcm], without
an adjacent letter on either side (enforced using regex C<\\b>).
A single match must be in consistent case, but either case is ok.
Experimental. Requires installing Perl's C<Roman> module
(L<http://search.cpan.org/~chorny/Roman/lib/Roman.pm>).
=item * B<--verbose> OR B<-v>
Provide more detailed messages. Repeatable.
In particular, show what each filename changes to as it progresses through the
selected optional changes.
=item * B<--version>
Display version info and exit.
=item * B<-x> OR B<--normalizeExtensions>
Normalize a variety of extensions to 3-letter lower-case form
(use I<--help-x> to display a list).
See also I<--addExtension> and I<--extChanges>.
=back
=head1 Known bugs and limitations
Need a conflict resolution suffix for case-insensitive file systems if the
rename only changes case (and thus looks different to the code, but not to a
case-insensitive filesystem).
I<--filesystem> is unfinished.
Changes with I<--extensions> put in 2 dots.
Unicode filenames are not thoroughly tested (and handling may depend on how
your locale is set).
Serial numbers with I<--resolve> may be placed after a file extension;
the fix is little tested.
There is no option to change the set of allowed characters with I<--clean>.
There is no option to change the set of extension mappings used by I<-x>.
Regexes may include an C<options> portion, but it is not used.
Does not know about some backup conventions, such as foo~, #foo#, or
C<emacs>'s ability to put backups into a separate directory:
(setq backup-directory-alist `(("." . "~/.saves")))
I<--pull> doesn't do anything smart if there are
embedded "//", "/./", or "/../" in any paths. It should probably
call C<realpath> or similar first.
It would be nice to be able to pull user- and group-names,
image and/or file-system metadata, etc. into filenames. On Mac OS,
file-system metadata (xattrs)is available with commands like:
mdls [files]
mdls -name kMDItemWhereFroms [files]
Date formats should be more flexible, controllable, and localizable.
There should be an option to remove a matched date, not just copy it to
the front.
=head2 Security implications
Because regex changes (see I<-e>) can include back- and variable-references
on the right-hand side ($1, \1, etc.), the changes are carried out using an
I<eval>(). This could lead to injection vulnerabilities.
=head1 Related commands
=head2 *nix commands
The *nix C<rename> command is similar, and commonly available on Linux
(but not on BSD and Mac OSX).
However, it can only do shell wildcards (not full regular expressions).
Some Linuces have a C<rename> that uses Perl regexes.
However, the usual C<rename>s lack features such as
I<--ancestor>, I<--bactrianize>, I<--camelize>, I<--clean>, I<--dates>,
I<--moddates>, I<--resolve>, I<--pad>, I<--pull>, and I<-x>.
Most also lack name conflict resolution, a I<--dry-run> mode, etc.
Simple batch renames can also be done with the C<bash for> command:
for x in abc*; do
y=`echo "$x" | sed "s/foo/bar/g"`
echo "Renaming file '$x' to '$y'"
mv $x $y
done
In `zsh` as opposed to `bash` you can use `zmv` to achieve renames like:
zmv "(*).jpeg" "$1.jpg"
zmv "(*)-backup.(*)" "backups/$1.$2"
=head2 SJD commands
C<whereFrom> -- Has a I<--pull> option that does renaming like
the I<--pullURI> option here (by default it just displays the source URI).
C<whereFrom> can also re-organize files into directory trees based on the paths
in their source URIs.
C<flattenDirs> -- Move all descendants of the current directory up into the
current directory, prefixing the intermediate directory names to the filenames
(separated by "_") instead of "/").
C<groupFiles> -- Normalize file names and move files into sub-folders
based on common parts of their names, ignoring any final digits.
C<lowerExtension> -- Force file extensions to lower case.
C<splitBigDir> -- Group files into several other directories, based on the
first letter(s) of the files' names (or a few other things).
=head1 To do
=over
=item * Apparently MacOS favors Unicode NFD (Canonical Decomposition),
while others like NFC (Canonical Decomposition + Composition). Deal.
=item * Add synonym options for case types like:
camelCase (or lowerCamelCase) — myVariableName
PascalCase (or UpperCamelCase) — MyClassName
snake_case — my_variable_name
SCREAMING_SNAKE_CASE — MY_CONSTANT
kebab-case (or lisp-case) — my-function-name
SCREAMING-KEBAB-CASE — MY-CONSTANT (rare)
Train-Case — My-Function-Name (HTTP headers)
flatcase — myvariablename (no separators at all)
UPPERFLATCASE — MYVARIABLENAME
=item * Watch for filesystem-specific reserved names, etc:
Windows:
Always reserved (any extension or none):
CON, PRN, AUX, NUL
COM1 through COM9
LPT1 through LPT9
Can't end with space or period (gets silently stripped)
<>:"|?* are illegal in names
Path component can't be just . or ..
macOS:
: is illegal (legacy from HFS using it as path separator)
Unix/Linux:
Only / and null are truly illegal, but newlines are problematic
For munging reserved names, common strategies:
Prefix with _ → _CON.txt
Append _ → CON_.txt
Add tilde → CON~.txt
Percent-encode → %43ON.txt (ugly but reversible)
=item * Check and warn on git files even if they don't ask?
=item * Warn/fix hyphen-initial filenames, names w/ spaces
(in *nix these are annoying though not illegal).
=item * Option to operate *only* on directories.
=item * I<--clean> should also do I<--addExtension> 'txt' (for non-dirs).
=item * Option to make I<--camelize> and I<--bactrianize> use (e.g.) "_" instead
of " " (can do with a regex change in the meantime).
=item * Make I<--bactrianize> not put space after hyphens.
=item * Unicode issues, esp nbsp (U+A0) with I<--dates>.
=item * "To" vs "_to_" vs "2"?
=item * Feature to increment, or make contiguous, numeric portions of filenames?
Cf C<nextFilename>.
=item * Do something better with case-change-only renames on case-insensitive systems.
=item * Option to affect only the first (or Nth?) match with I<--expr>.
=item * Make --dropOriginal apply to other
options (not just --pullContent), that similarly apend brand-new,
likely-unique strings to the filenames.
=item * Port to Python and integrate PowerWalk.py.
=item * Options to set properties on files, like Mac OS label? (see list below)
l<http://superuser.com/questions/168927/>
com.apple.metadata:_kMDItemUserTags
=item * Idea of pulling metadata from PDF into filename.
L<https://stackoverflow.com/questions/44598758> or "cermine".
Cf L<https://academia.stackexchange.com/questions/139733/how-to-manage-publications-on-a-local-computer?rq=1>
L<https://stackoverflow.com/questions/50575957/how-to-robustly-extract-author-names-from-pdf-papers>
L<https://www.tutorialexample.com/python-extract-pdf-paper-title-by-content-not-by-metadata-a-step-guide-python-tutorial/>
L<https://stackoverflow.com/questions/1813427/extracting-information-from-pdfs-of-research-papers>
L<https://pypi.org/project/scholarly/>
PyPDF2, cb2bib, TET, Cermine.
=item * Add a way to reference Mac fs metadata in I<--expr> RHS.
=item * pull checksum of the file into metadata or name?
=item * I<--ePad> only allows I<left> padding at present.
=item * Various date/time improvements:
=over
=item * Option to add periodic dates (esp. by month) to a series of files,
for example downloaded bank statements that the bank just sends as "statement.pdf".
Just do in the order specified; that works whether they're in dated folders
(those could also be done via --pull), or all in one with OS-generated
names like "foo copy 5.pdf". E.g.:
renameFiles --startMonth 2022-03 ./bankOfSumeria/statement*.pdf
=item * Access to additional data to pull into name.
=item * Allow localized date formats and month names, or C<strftime> formats.
=item * Add times and datetimes to I<--addstat>.
=item * Option to extract MIME "Date:" from .eml files.
=item * Option to normalize date format without moving to start/end.
=item * Make sure pulling in [abcm]time doesn't duplicate date already present?
=back
=back
=head1 History
=over
=item * 2006-12-18: Written by Steven J. DeRose.
=item * 2007-01-23: Tweak doc. Add -p, -x.
=item * 2007-12-03 sjd: strict.
=item * 2009-06-24 sjd: Debug....
=item * 2009-08-20 sjd: Debug....
=item * 2010-09-12 sjd: Cleanup, Getopt.
=item * 2011-05-25 sjd: More cleanup. Don't skip first file listed. Add I<--dirs>.
=item * 2012-02-06 sjd: Move regex to option. Allow non-Latin \\w, I<--test>.
Add C<doRename()> and change from system C<mv> to Perl rename(). sjdUtils.
Put serializers before extension! Add I<--pull> to pack ancestor dir
name(s) onto front of filenames.
=item * 2012-04-10 sjd: Add I<--force>, I<--recurse>, I<--ancestor>, I<--lc>.
=item * 2013-01-09 sjd: Clean up. Add I<--camelize>. OS stuff like "Copy N of ...".
Add I<--dates>, I<--addExtension>, I<--toEnd>, I<--copies>.
=item * 2013-10-15: I<--pull> w/o I<--expr>. Add I<--ignoreCase>, I<--sep>.
I<--copies> earlier. Use C<vMsg()>. Clean up path vs. name distinction.
=item * 2013-12-21: Add I<--pullURI>.
=item * 2014-01-09ff: Fix I<--dates>, I<--pullURI>. Add I<--moddates>.
=item * 2014-03-27: Add I<--ePad>.
=item * 2014-05-09ff: Add I<--unescapeURI>, I<-x>. Count/report extension changes.
=item * 2014-08-22: Fix recursion. Separate splitPath, joinPath.
=item * 2014-12-15: Add I<--bactrianize>.
=item * 2015-02-25ff: Fix bugs that prevented backreferences with I<-e>,
and RHS like "11-4" becoming "7" due to eval. Add I<--dot>, fix I<--dates>.
=item * 2015-08-04: Remember to include Encode. Use C<strftime()> for month names.
Change I<--moddate> to I<--addStat statName>.
=item * 2017-01-31: Add I<--unroman> to convert Roman to Arabic numerals.
=item * 2018-01-26: Add conflict check immediately before C<doRename()> acts.
=item * 2018-04-12: Missing return for I<--expr>. Add I<-v> messages. Fix I<--addStat>.
=item * 2018-08-09: Finish I<--extChanges>. Add I<--uc>. Split out variousChanges().
=item * 2018-10-16: Use C<file> command with I<--addExtension> "!".
=item * 2019-10-29: Clean up expr parsing logic. Add I<--dropExtensions>, I<--onlyExt>.
Start I<--kmdAdd>, I<--kmdList>.
=item * 2020-06-26: New layout. Add I<--dateYears>.
=item * 2020-10-12: Rename I<--kmdXXX> to I<--xattrXXX>, I<--onlyExt> to
I<--onlyExtensions>. Add I<--extensions> synonym.
=item * 2021-02-16: Add I<--lcExtensions>.
=item * 2021-04-27: Start I<--filesystem>.
=item * 2022-01-07: Fix bug with name conflicts when there's no extension.
Still not great for case-insensitive file-systems when you change only case.
But now notices and reports them, at least.
=item * 2022-03-30: Clean up doc. Drop alogging.
=item * 2022-07-18: Put alogging back.
=item * 2022-08-14: Add --dropOriginal.
=item * 2022-09-29: Add "git mv" support via my C<versionStatus.py>.
=item * 2022-12-08: Clean up help text and file-system spec table.
=item * 2024-06-05: Improve stat reporting. Drop use of C<versionStatus.py>.
Make --dateOutput an option, and integrate strftime. Add --dateTest.
=back
=head1 Rights
Copyright 2006-12-18 by Steven J. DeRose. This work is licensed under a
Creative Commons Attribution-Share Alike 3.0 Unported License.
For further information on this license, see
L<https://creativecommons.org/licenses/by-sa/3.0>.
For the most recent version, see L<http://www.derose.net/steve/utilities> or
L<https://github.com/sderose>.
=cut
###############################################################################
# Get month names from locale (see http://perldoc.perl.org/perllocale.html
# and man(7) strftime (days of week are %a %A)
#
my %monthDict = ();
for (my $i=0; $i<12; $i++) {
# strftime counts months from 0-11, we want 1-12....
my $m = strftime("%B", 0, 0, 0, 1, $i, 96); # Full name
$monthDict{$m} = $i + 1;
$m = strftime("%b", 0, 0, 0, 1, $i, 96); # Abbreviated name
$monthDict{$m} = $i + 1;
}
my $monthExpr = join("|", keys(%monthDict));
# Allow for no-break space U+00A0, which is NOT included in \s!
my $nbsp = chr(0xA0);
# TODO: \\b is bad if adjacent char is "_".... neg lookbehind: (?<![\w_])
# TODO: Accepts mdays like 39, mon like 29, period after full month name,....
#
my $date1expr = qr/\b([01]?\d)\/([0-3]?\d)\/(\d{4})\b/; # 12/31/1999
my $dateUKexpr = qr/\b([0-3]\d)\/([01]\d)\/(\d{4})\b/; # 31/12/1999
my $date2expr = qr/\b($monthExpr)\.?[\s\xA0]*([0-3]?\d?)?[,\s\xA0][\s\xA0]*(\d{4})\b/;
my $date3expr = qr/\b([0-3]?\d?)[,\s\xA0]($monthExpr)\.? (\d{4})\b/; # 31 Dec 1999
my $date4expr = qr/\b(\d{4})-([01]\d)(?:-([0-3]?\d))?\b/; # 1999-12-31 (ISO 8601)
my $date5expr = qr/\b(\d{4})([01]\d)([0-3]\d)\b/; # 19991231
# Names and indexes of the fields of a file stat block.
# Strings that user can use to specify what to add with --addStat.
#
my %statKeys = (
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
"adate" => 8,
"cdate" => 10,
"mdate" => 9,
# "atime" => 8,
# "ctime" => 10,
# "mtime" => 9,
# "adatetime" => 8,
# "cdatetime" => 10,
# "mdatetime" => 9,
"blksize" => 11,
"blocks" => 12,
"dev" => 0,
"gid" => 5,
"ino" => 1,
"mode" => 2,
"nlink" => 3,
"rdev" => 6,
"size" => 7,
"uid" => 4,
);
# Mac filesystem xattr metadata (all keys start with "kMDItem").
# See metadata attributes for a file with "mdls" command on Mac.
# Planning to add a way to reference these in --expr RHS.
#
my %macMeta = (
# Name Example value
"kMDItemContentCreationDate" => "2015-03-17 15:28:56 +0000",
"kMDItemContentModificationDate" => "2015-03-17 15:28:56 +0000",
"kMDItemContentType" => "public.tab-separated-values-text",
"kMDItemContentTypeTree" => [
"public.tab-separated-values-text",
"public.delimited-values-text",
"public.text",
"public.data",
"public.item",
"public.content"
],
"kMDItemDateAdded" => "2015-03-17 15:28:56 +0000",
"kMDItemDisplayName" => "lexicon.tsv",
"kMDItemFSContentChangeDate" => "2015-03-17 15:28:56 +0000",
"kMDItemFSCreationDate" => "2015-03-17 15:28:56 +0000",
"kMDItemFSCreatorCode" => "",
"kMDItemFSFinderFlags" => "0",
"kMDItemFSHasCustomIcon" => "(null)",
"kMDItemFSInvisible" => "0",
"kMDItemFSIsExtensionHidden" => "0",
"kMDItemFSIsStationery" => "(null)",
"kMDItemFSLabel" => "0",
"kMDItemFSName" => "lexicon.tsv",
"kMDItemFSNodeCount" => "(null)",
"kMDItemFSOwnerGroupID" => "20",
"kMDItemFSOwnerUserID" => "501",
"kMDItemFSSize" => "15957",
"kMDItemFSTypeCode" => "",
"kMDItemKind" => "Plain Text Document", # see below
"kMDItemLogicalSize" => "15957",
"kMDItemPhysicalSize" => "16384",
"kMDItemAuthor" => "", # Some programs set this: many don't
"kMDItemContributors" => "", #
"kMDItemCountry" => "", #
"kMDItemCreator" => "", #
"kMDItemLastUsedDate" => "", #
"kMDItemTextContent" => "", #
"kMDItemTitle" => "", #
"kMDItemWhereFroms" => "", # URI downloaded from (when applicable)
"kMDItemComposer" => "", # iTunes often sets this
# Additional Image meta (see C<spot -h>)
"kMDItemAlternateNames" => [
"Screen Shot 2014-05-10 at 8.06.13 PM.png"
],
"kMDItemBitsPerSample" => "32",
"kMDItemColorSpace" => "RGB",
"kMDItemContentTypeTree" => [
"public.png",
"public.image",
"public.data",
"public.item",
"public.content"
],
"kMDItemHasAlphaChannel" => "0",
"kMDItemIsScreenCapture" => "1",
"kMDItemOrientation" => "0",
"kMDItemPixelCount" => "101952",
"kMDItemPixelHeight" => "216",
"kMDItemPixelWidth" => "472",
"kMDItemProfileName" => "Color LCD",
"kMDItemResolutionHeightDPI" => "144",
"kMDItemResolutionWidthDPI" => "144",
"kMDItemScreenCaptureType" => "selection",
);
# Some values, there are many more. Some of these seem redundant or
# inconsistent. Where do they actually come from?
#
my @kMDItemKind_values = (
"Alias",
"Disk Image",
"Folder",
"gzip compressed archive",
"ZIP archive",
# Code
"C Source",
"C++ Source",
"Emacs Lisp Source File",
"JavaScript script",
"Objective-C++ Source",
"Perl Source",
"PHP Script",
"Python Bytecode Document",
"Python Script",
"Python Source",
"Script",
"Shell Script",
"Unix Executable File",
# Document-ish
"BBEdit text document",
"CSS style sheet",
"CSV Document",
"Document Type Definition",
"Document",
"HTML document",
"Markdown Document",
"JSON Document",
"Keynote Presentation",
"Microsoft Excel Document",
"Microsoft Word Document",
"OpenDocument Text (.odt) Document",
"Oxygen XML Editor project",
"Pages Document",
"Rich Text Document",
"SimpleText Document",
"Text",
"TSV Document",
"vCard",
"XML document",
"XML Document",
"XML Schema Document",
# Image-ish
"ConceptDraw CDDZ Document",
"Graph Markup Language",
"JPEG image",
"Panasonic raw image",
"PDF document",
"Plain Text Document",
"PNG image",
"PostScript document",
"PostScript",
);
# See https://en.wikipedia.org/wiki/Comparison_of_file_systems
#
my $BY = "bytes"; my $UC = "UChar";
my $AS = "ASCII"; my $MS = "cp1252";
my $U8 = "UTF-8"; my $U2 = "UCS-2"; my $U6 = "UTF-16";
my $KB = 1<<9; my $MB = 1<<19; my $GB = 1<<29;
my $TB = 1<<39; my $PB = 1<<49; my $EB = 1<<59; my $ZB = 1<<69;
my $UNLIM = -1;
my $XX = 0; # Unknown or unspecified value
# Expressions for banned characters
my $NULL = "[\\x00]";
my $NULLSOL = "[\\x00/]";
my $CPMBAN = "[<>.,;:=?*\\[\\]]";
my $FAT16BAN = "[\\x00-\\x1F \"*+,./:;<=>?\\\\[\\]]";
my $FAT16LFN = "[\\x00\"*/:<>?\\\\|]";