5

I have many files of the form

sw001
sw002
sw003
...

I want to insert a period between the sw's and the number values. How can I accomplish this?

maxschlepzig
  • 57,532
Paul
  • 9,423

3 Answers3

8

If you don't have rename and don't feel like downloading it, use this:

for file in sw*; do
    mv "$file" "${file/sw/sw.}"
done
Kevin
  • 40,767
  • Be aware that the pattern substitution ${file/sw/sw.}" also matches files like FOOsw001. Besides - this kind of substitution is not supported by all shells. Removing a prefix pattern should be more appropriate and portable: "$sw.{file#sw}" – maxschlepzig Mar 02 '12 at 19:16
  • 2
    @maxschlepzig I suppose it would, but because of the glob all names it encounters necessarily begin with sw. Good to point out in general though. – Kevin Mar 02 '12 at 19:20
5

On Linux:

rename 'sw' 'sw.' sw*

On Debian, Ubuntu and derivatives, use rename.ul instead of rename (rename is a different file renaming command on those distributions).

rsaw
  • 1,006
1

If you can can express the transformation as a Perl regular expression, rename that ships with Perl is a great choice. It applies a Perl expression to each filename, then changes the name if it is different. Often, a Perl regular expression substitution is what you want:

rename 's/sw/sw./' sw*

This is different from the rename(1) that ships with util-linux-ng, but normally the Perl version is the default. See man 1 rename to check which one your system has.

  • Can you help me to understand what the / notation means? – Paul Mar 02 '12 at 18:09
  • Hopefully that edit is clearer: the man page was for a different utility with the same name, and I didn't notice because it was close enough. The Perl rename applies a Perl expression; 's///' is a regular expression substitution. – Daniel Pittman Mar 02 '12 at 18:18
  • 1
    If this rename expression is indeed a regular expression, the . character would mean "any one character", so it should be escaped in order to be taken literally. –  Mar 02 '12 at 18:45
  • 1
    @hesse, it would in the match part, not in the replacement part. :) – Daniel Pittman Mar 02 '12 at 19:05
  • The Perl version is the default in Debian and derivatives including Ubuntu. It's not shipped by other distributions. – Gilles 'SO- stop being evil' Mar 02 '12 at 23:01