-1

I need to rename files by swaping some text. I had for example :

eMail - 2015-11-28 1926.eml second mail - 2016-07-26 1245.eml third mL 2016-11-26 1410.eml 4-mail 2017-05-21 0105.eml

...

and I want them

2015-11-28 1926 eMail - .eml 2016-07-26 1245 second mail - .eml 2016-11-26 1410 third mL.eml 2017-05-21 0105 4-mail.eml

... a part of a way you could find here:

i tried ls *.pdf | awk -F"[_.]" '{print "mv "$0" "$2"_"$1"."$3}' | sh
from > swap filename example
that was running goog, but not practical for .eml-files.

second swap filename example looks good too
but i am a bit stupid to solve the problem

urban KS
  • 1
  • 2

1 Answers1

0

If regex is available (bash version >= 3.2), please try the following:

for f in *.eml; do
    if [[ $f =~ ^(.+)\ +([0-9]{4}-[0-9]{2}-[0-9]{2}\ +[0-9]+)\.eml$ ]]; then
        newname="${BASH_REMATCH[2]} ${BASH_REMATCH[1]}.eml"
        mv -- "$f" "$newname"
    fi
done
  • The regex breaks down the filename into "date + number substring" and "preceding substring" then assigns bash variable ${BASH_REMATCH[@]} to the captured groups.
  • Then newname is assigned to a swapped filename.
tshiono
  • 21,248
  • 2
  • 14
  • 22