2

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

aaaaaa_bb_cccc_ddddd_ee.jpg 

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

cccc_ddddd_ee.jpg 

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

ddddd_ee.jpg 

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?

2 Answers 2

4

With the Perl Rename utility,

$ ls aaaaaa_bb_cccc_ddddd_ee.jpg $ 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.

3

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
  • 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.). Commented Sep 20, 2020 at 16:57
  • 1
    @Quasímodo Good to know. Thank you! Commented Sep 20, 2020 at 16:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.