Search code examples
regexunix

How can I use the rename command with regex to remove the last part of a filename but keep the extension?


I have a list of files that use the following naming convention:

filename-test-12345.txt

I am trying to remove the "-test-12345" part of each file but keep the .txt extension. I've tried to use the rename command with regex but unfortunately my syntax is incorrect:

rename -n 's/(.*).{15}$/$1.txt/' * 

Does anyone know how to modify the regex to get it to display the desired output ie. filename.txt? I am not looking to write a script, as this is just a one off list of files in a folder that I need to rename.


Solution

  • Using Perl's rename (usable in any OS):

    rename -n 's/.{15}$/.txt/' * 
    

    or

    rename -n 's/-\w+-\d+//' *
    

    or

    rename -n 's/^(\w+)-.*(\.txt)/$1$2/'
    

    or

    rename -n 'my @a = split /[-.]/; s/.*/"$a[0].$a[-1]"/' *
    

    or better written:

    rename -n 's/.*/join ".", +(split m|[-.]|)[0, -1]/e' *
    

    Output:

    rename(filename-test-12345.txt, filename.txt)
    

    remove -n when happy with the output.


    If you don't have the good output, your rename implementation looks not the good one, check my link with deep explanations and how to use Perl's rename.


    Short regex memo:

    • \d: a digit
    • \w: word character: a-z, A-Z, 0-9, _