10

The man page gives two examples:

rename 's/\.bak$//' *.bak
rename 'y/A-Z/a-z/' *

So it's either s or y and then /replaceThis/withThis

What does the leading s and y mean? Are there other options?

wjandrea
  • 14,504

2 Answers2

14

In the first case:

rename 's/\.bak$//' *.bak

you are running a regular expression against filenames and replacing the matching part of expressions (.bak at the end of a file name) with the second expression (which is empty).

In the second case:

rename 'y/A-Z/a-z/' *

you are matching against the regular expression pattern space and transliterating to the target. In other words, the range A-Z is changed to the range a-z, making the filenames lower case.

I suggest you look at the man page for sed for more commands and more details. I believe the 's' command is used most often. As well, regex (section 7) and perl documentation may also be of help. In particular, here's a tutorial on perl and regular expressions.


From man sed:

s/regexp/replacement/    
       Attempt to match regexp against the pattern space.  If  success‐
       ful,   replace  that  portion  matched  with  replacement.   The
       replacement may contain the special character & to refer to that
       portion  of  the  pattern  space  which matched, and the special
       escapes \1 through \9 to refer  to  the  corresponding  matching
       sub-expressions in the regexp.

y/source/dest/  
       Transliterate  the  characters in the pattern space which appear
       in source to the corresponding character in dest.
wjandrea
  • 14,504
John S Gruber
  • 13,436
-2

Thanks for the above explanation of this command. It was helpful enough for me to use rename to batch change the extensions to a whole group of files. I thought it would be good to share what I've learned.

In this example I have a group of files with the following names:

test1.old
test2.old
test3.old

I want to change all of the extensions from ".old" to ".new"

(In this example, the files are on the Desktop)

My terminal line reads as follows:

user@linuxsystem:~/Desktop$ rename 's/\.old$/.new/' *.old

In this example the syntax is as follows:

rename 's/\[REPLACE$]/[NEW TEXT]/' [TARGET]

So in this case, REPLACE is ".old", NEW TEXT is ".new" and the TARGET is "*.old" meaning any file with the extension .old

I realize that writing it out in this manner may seem redundant for seasoned users, but as I non-expert, I often wish someone break things down like this so I can follow it.

Thanks again for the info! I couldn't have figured this out without the post above!