I’ll assume that you are sure that none of your filenames contain newlines,
or that you have some way of dealing with that possibility.
First, manipulate your filenames with sed
:
% command_to_list_filenames | sed 's/.*\.\([0-9][0-9][0-9][0-9]\)\..*/\1.&/'
2001.Could Be A Title.2001.prop.ext1
1989.Another Potential Title.1989.prop.ext2
%
The s
(substitute) command in the sed
command
treats each line as a sequence of the following:
- Any number of any character (
.*
),
- An actual period (
\.
),
- Four digits (
[0-9][0-9][0-9][0-9]
),
- Another actual period (
\.
), and
- Another character sequence (
.*
).
Note that the year ([0-9][0-9][0-9][0-9]
) is enclosed
between \(
and \)
, forming a group.
The substitute command then replaces the string with
- The grouped characters, i.e., the year (
\1
),
- A period (
.
), and
- The entire input line (
&
).
Then it’s a simple matter of sorting the lines by the year
(which now appears at the beginning of the line) and stripping off the year:
% command_to_list_filenames | sed 's/.*\.\([0-9][0-9][0-9][0-9]\)\..*/\1.&/' | sort
1989.Another Potential Title.1989.prop.ext2
2001.Could Be A Title.2001.prop.ext1
% command_to_list_filenames | sed 's/.*\.\([0-9][0-9][0-9][0-9]\)\..*/\1.&/' | sort |
sed 's/^[0-9][0-9][0-9][0-9].//'
Another Potential Title.1989.prop.ext2
Could Be A Title.2001.prop.ext1
%
The sed
command can be trivially modified to handle the other pattern.
And sed
can take input from a file instead of a pipe:
% sed 's/.*(\([0-9][0-9][0-9][0-9]\)).*/\1.&/' list_of_directory_names | sort |
sed 's/^[0-9][0-9][0-9][0-9].//'
Charlie Fisher's (1989)
Badger Bodger (2001)
%
Note that this works fine with text that contains periods or parentheses, e.g.,
Dr. Strangelove.1964.foo
Mrs. Doubtfire.1993.bar
so long as they are not followed by four-digit numbers.
You can leave off the second .*
if you want:
% command_to_list_filenames | sed 's/.*\.\([0-9][0-9][0-9][0-9]\)\./\1.&/'
2001.Could Be A Title.2001.prop.ext1
1989.Another Potential Title.1989.prop.ext2
%