Marco
Marco

Reputation: 179

How to rename multiple files?

In a folder I have several files with the following name-structure (I write just three examples):

F_001_4837_blabla1.doc
F_045_8987_blabla2.doc
F_168_9092_blabla3.doc

What I would do is to use a BASH command to rename all the files in my folder by deleting the first underscore and the series of zeros before the first number code obtaining:

F1_4837_blabla1.doc
F45_8987_blabla2.doc
F168_9092_blabla3.doc

Upvotes: 1

Views: 157

Answers (1)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20873

shopt -s extglob

for f in *; do
  echo "$f: ${f/_*(0)/}"
  # mv "$f" "${f/_*(0)/}"   # for the actual rename
done

output

F_001_4837_blabla1.doc: F1_4837_blabla1.doc
F_045_8987_blabla2.doc: F45_8987_blabla2.doc
F_168_9092_blabla3.doc: F168_9092_blabla3.doc

Parameter Expansion

Parameter expansion can be used to replace the content of a variable. In this case, we replace the pattern _*(0) with nothing.

${parameter/pattern/string}
       Pattern substitution.  The pattern is expanded to produce a pat-
       tern just as in pathname expansion.  Parameter is  expanded  and
       the  longest match of pattern against its value is replaced with
       string.  If pattern begins with /, all matches  of  pattern  are
       replaced   with  string.   Normally  only  the  first  match  is
       replaced.  If pattern begins with #, it must match at the begin-
       ning of the expanded value of parameter.  If pattern begins with
       %, it must match at the end of the expanded value of  parameter.
       If string is null, matches of pattern are deleted and the / fol-
       lowing pattern may be omitted.  If parameter is @ or *, the sub-
       stitution  operation  is applied to each positional parameter in
       turn, and the expansion is the resultant list.  If parameter  is
       an  array  variable  subscripted  with  @ or *, the substitution
       operation is applied to each member of the array  in  turn,  and
       the expansion is the resultant list.

Extended pattern matching

Extended pattern matching allows us to use the pattern *(0) to match zero or more 0 characters. It needs to be enabled using the extglob setting.

If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized.  In  the  following
description, a pattern-list is a list of one or more patterns separated
by a |.  Composite patterns may be formed using one or more of the fol-
lowing sub-patterns:

       ?(pattern-list)
              Matches zero or one occurrence of the given patterns
       *(pattern-list)
              Matches zero or more occurrences of the given patterns
       +(pattern-list)
              Matches one or more occurrences of the given patterns
       @(pattern-list)
              Matches one of the given patterns
       !(pattern-list)
              Matches anything except one of the given patterns

Upvotes: 2

Related Questions