2

I'm trying to use the command line "rename" to change some filenames that contain several periods. For example: this.is.a.file.name.txt

After looking around a bit I've found some examples that almost get me there, but I can't seem to get it to work as required. Needless to say, I'm a very green beginner with regex's.

I've tried this:

rename -v -n 's/\.(.+?)(?=\.)//' this.is.a.file.name.txt

Which results in this:

this.a.file.name.txt

I've tried to modify the examples found in the following resources, but I'm stuck. PHP Regex: Select all except last occurrence Regex not replacing the last occurrence of a match

Community
  • 1
  • 1
stotrami
  • 159
  • 1
  • 1
  • 11
  • 2
    Could you provide a more clear example of what the input and desired output would be? Are you trying to remove all but the file extension? – woemler Feb 03 '13 at 22:18
  • @willOEM Yes, that's correct, I want to keep just the file extension. So the desired result would be: `thisisafilename.txt` – stotrami Feb 03 '13 at 23:17

1 Answers1

5

Your regular expression is not quite right for a couple of reasons. First, the thing you're substituting the empty string for should be just the period, whereas you're matching from a period to everything that is the next period and removing that. Also, you're only doing it once.

The regular expression you want is /\.(?=.*\.)//g, which says match a period that is followed by a zero-width assertion of any number of characters and another period, and do that as many times as it can.

David M
  • 4,325
  • 2
  • 28
  • 40
  • 1
    This works perfectly. I simply prepend this with "s" and receive this verification: `$ rename -n -v 's/\.(?=.*\.)//g' sdv.sdgs.hsdgh.sdg.sdf` `sdv.sdgs.hsdgh.sdg.sdf renamed as sdvsdgshsdghsdg.sdf` – stotrami Feb 03 '13 at 23:21