I have a list of files, in different folders, named like


In some of them, I need to remove everything up to the second _, so they become


In others (already in a separate folder), I need to remove everything up to the third _


I know commands such as rename, which use some REGEX, but I don't know the exact expression for this case. How can I do that on Linux terminal?


With the Perl Rename utility,

$ ls
$ rename -n 's/([^_]*_){2}//' *
rename(aaaaaa_bb_cccc_ddddd_ee.jpg, cccc_ddddd_ee.jpg)
$ rename -n 's/([^_]*_){3}//' *
rename(aaaaaa_bb_cccc_ddddd_ee.jpg, ddddd_ee.jpg)

The -n flag tells Rename to output what it would do. If you remove -n, the modifications will be applied.

The * will expand to every file in the current directory. In the example above, there was only one file, but Rename can operate on multiple files in a single run, in which case * is faster instead of a shell loop.

s/([^_]*_){2}// means: substitute every occurrence of the ([^_]*_){2} regular expression in filenames by nothing. The regex means: any number of non-underscores [^_]* followed by a underscore _ repeated twice.


To eliminate everything up to the second _

rename -n 's/[^_]*[_][^_]*[_]//' *

To eliminate everything up to the third _

rename -n 's/[^_]*[_][^_]*[_][^_]*[_]//' *

Remove the -n to effectively change the filenames, and not just test.

  • 2
    Nice to see you came up with a solution! Just a note: It is good to quote the regex so as to prevent the shell from expanding the * as globs (highly unlikely in this case, though, you would have to have a very weirdly named file for that to happen.).
    – Quasímodo
    Sep 20 '20 at 16:57
  • 1
    @Quasímodo Good to know. Thank you!
    – Rodrigo
    Sep 20 '20 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.