I can use the following command successfully, and I'm quite confident with this command to make other combinations:
rename 's/\.htm/\.html/' *.htm
However I want to know more about it, especially about s
in it. They say it is a Perl expression. I haven't learned Perl programming language, so I have no idea why there is such a 's/\.htm/\.html/'
argument. Would you tell me what it is?? Thanks for reading.
In general
rename
renames the filenames supplied according to the rule specified as the first argument of the command. The the filenames are supplied by the arguments that follow the first one.The first argument in the example command (
rename 's/\.htm/\.html/' *.htm
) has fur parts, where in this case/
is a delimiter of these parts:The
s
command means substitute:s/<old>/<new>/
. Match the regular-expression against the content of the pattern space. If found, replace matched string with replacement.Regular expression that matches to the strings that should be substituted. In the current case this is just the string
.htm
.In most regular expressions the dot
.
matches to every character. In this case we want to use the dot literally, so we need to escape its special meaning by using the back slash\
(quoting a single character).Replacement of the sting/regexp matched to 2.
Flag that is not presented in the current example. It could be for example the flag
g
- apply the replacement to all matches to the regexp, not just the first. Let's assume we have a file namedmy.htm-file.htm
:The original command
rename 's/\.htm/\.html/' *.htm
will rename the file in this way:my.html-file.htm
. Look at the bottom of the answer how to avoid this problem.By adding the
g
flag -rename 's/\.htm/\.html/g' *.htm
- the new filename will be:my.html-file.html
.According to the filenames:
*
can represent any number of characters (including zero, in other words, zero or more characters). The shell will expand that glob, and it passes the matching filenames as separate arguments torename
So*.htm
- will match to all filenames in the current path that end with the string.htm
. For example if you have1.htm
,2.htm
,3.htm
,4.htm
, and5.htm
thenrename 's/\.htm/\.html/' *.htm
passes exactly the same arguments to rename as running:The whole command (
rename 's/\.htm/\.html/' *.htm
) could be read in this way:Let's go back to the example when we have a file named
my.htm-file.htm
. Probably we want to change the last part of the filename so called extension after the last dot. For this purpose we should modify therename
command in this way:Where the
$
sign matches to the end of the line and literally means "read backward".References: