I’m currently writing a bash script for renaming files.
Every file looks like this *_#.ext where * can be anything and # a 9 digits number. In this example, ill stick with 3 digits instead.
Here is a basic example of what it should do:
Input: example1_123.jpg
Output: example1.jpg
Simple enough? Right:
#!/bin/bash
filename="example1_123.jpg"
echo ${filename/_[0-9][0-9][0-9]/}
Output: example1.jpg
This works… as long as the input isn’t something like this filename:
example2_123.jpg_987.jpg
The file will be renamed to example2.jpg_987.jpg instead of example2_123.jpg.jpg
i tried using $ for end of line, but this breaks it, as $ is used for variables:
#!/bin/bash
filename="example2_123.jpg_987.jpg"
echo ${filename/_[0-9][0-9][0-9].jpg$/}.${filename/*./}
Output: example2_123.jpg_987.jpg.jpg
\$ also doesn’t work. I’m clueless…
Can anyone help me getting it to work the way I need it to?
P.S. [0-9]{3} instead of [0-9][0-9][0-9] also breaks it. If someone knows how to shorten it, please say so 🙂
Use:
This will do what you want.
Surround
$(...)with double quotes should you have space names in$f.This is sed, therefore a classical regex dialect, therefore grouping, alternatives and quantifiers (well, except
*) all need to be preceded with a backslash… The “canonical” regex really is: