How to remove numbers from filename

Hi all,

Can I edit this script:

find . -type f | while read i;do [ "$i" != "${i//abc/}" ] && mv "$i" "${i//abc/}" ;done

so that it will not only take out abc from the filename but also take out any numbers [Date, as in the year i.e. 2009 or any other year] that might be in the filename as well.

An example would be,

Input:
filename abc 2009.mov

Output:
filename.mov

or

Input:
filename.abc.2009.mov

Output:
filename.mov

Regards :slight_smile:

use

sed 's/\(^[aA-zZ]*\).*\(\.[aA-zZ]*$\)/\1\2/g'

cheers,
Devaraj Takhellambam

In "${i//abc/}" abc is regarded as regular expression (regexp).
You need only to improve on the regexp to make it match what you want.
Regexp syntax for bash and ksh is a little different from the POSIX syntax (i.e. egrep).

  • abc matches just "abc" on any position
  • abc+([0-9]) matches "abc", followed by one or more decimal digits, on any position
  • abc *+([0-9]) matches "abc", followed by zero or more spaces, followed by one or more decimal digits, on any position
  • abc *+([0-9])$ matches "abc", followed by zero or more spaces, followed by one or more decimal digits, only if at the end of the filename

If you need to remove "abc" and the number, keeping what is in between, then you have to apply two successive ${i//.../} operations; alternatively you can use backreferences like:

${i//removethis1\(keepthis1\)removethis2/\1}

where keepthis1 and removethis1...removethis2 are regexp.

Well, I don't remember if bash or ksh93 really do support backreferences.

Colmar THAT'S AWESOME!!! THANK YOU FOR NOT ONLY GIVING ME THE SCRIPT I NEEDED BUT EXPLAINING THE WHOLE THING AS WELL.

Thanks Again. :D:D:D:D:D:D

No, it is a file globbing pattern not a regular expression.

Perhaps it is not a regular expression as formally defined in the computation theory, but it has almost the same power as the POSIX regexps have.

In the "turtle book" this syntax is referred as "regular expression":
[Chapter 4] 4.3 String Operators

It can even be the case that ${var//pattern/replace} has support for more metacharacters, because this syntax is found in ksh93 while the above book is about ksh88.

I believe a globbing pattern is one that has only two metacharacters, commonly known as "wildcards": * and ?

Extended globbing (as implemented in ksh and with the extglob option in bash) adds some very limited regular expression capabilities with a completely different syntax.

And [...] containing lists and/or ranges of characters.