I want to rename all folders from "dd.mm.yy" to "yy.mm.dd". How to do that in the shell?
Asked
Active
Viewed 407 times
6 Answers
5
A bash
solution renaming the directories in your current directory:
for f in [0-3][0-9].[01][0-9].[0-9][0-9]; do
[ -d "$f" ] && mv -v "$f" "${f:6}.${f:3:2}.${f:0:2}"
done

Freddy
- 25,565
3
Your question could use a little more information, therefore I am assuming:
- by all folders you mean all folders in the current directory
- while you mention regex, you neglected to mention OS, so I'm working on the basis that your
rename
version supports them
rename 's/^([0-9]{2})\.([0-9]{2})\.([0-9]{2})\//$3.$2.$1/' */
If you don't have rename
, or you do and it doesn't support regex, this is a more portable approach (albeit less elegant):
find . -mindepth 1 -maxdepth 1 -type d \
| sed 's ^./ ' \
| grep -E "^([0-9]{2}\.){2}[0-9]{2}$" \
| while IFS=. read dd mm yy ; do mv $dd.$mm.$yy $yy.$mm.$dd ; done

bxm
- 4,855
2
I recommend not using regexes, but rather resort to date tools when it comes to handling dates, e.g.
for dir in */; do echo mv $dir $(LC_ALL=C busybox date -uD '%d.%m.%Y' -d "$dir" "+%Y.%m.%d") ; done
(inspired by Force date to read Day/Month/Year.)
I included an echo
for "preview" mode.

Hermann
- 6,148
2
This is longer than a one-liner, but it's not making any assumptions about the date:
$ mkdir 12.12.12 01.02.99
$ perl -MTime::Piece -Mautodie -E '
opendir my $dh, ".";
while (my $f = readdir $dh) {
if (-d $f and $f =~ /^\d\d.\d\d.\d\d$/) {
my $t = Time::Piece->strptime($f, "%d.%m.%y");
rename $f, $t->ymd;
}
}
'
$ ls
1999-02-01/ 2012-12-12/

glenn jackman
- 85,964
1
A very easy way to do it, since already folders created.
ls -1d */|cut -f1 -d/ |awk -F"." '{print "mv " $0 " " $3"."$2"."$1"/"}' | bash

Chris Davies
- 116,213
- 16
- 160
- 287

Pradeep G
- 22
0
I know this is ugly (and fails in some situations...) but...
reg='^(..)\.(..)\.(..)/'
for a in */ ; do
[[ $a =~ $reg ]] && mv $a ${BASH_REMATCH[3]}.${BASH_REMATCH[2]}.${BASH_REMATCH[1]}
done

JJoao
- 12,170
- 1
- 23
- 45
YYYY-mm-dd
– glenn jackman Oct 21 '19 at 14:03