Reputation: 3
I need bash script, these are my files:
./2019-01-11_15-00-29_UTC.mp4
./2019-02-10_17-42-18_UTC.mp4
./2019-01-03_14-45-43_UTC.mp4
./2018-12-24_13-00-32_UTC.mp4
./2018-12-09_19-50-59_UTC.mp4
./2019-01-11_14-51-08_UTC.mp4
./2019-01-06_16-41-54_UTC.mp4
./2019-02-03_10-33-33_UTC.mp4
./2019-02-16_18-21-30_UTC.mp4
wanna make two folder 2018
& 2019
then move files own folder.
I use this code:
ls *.mp4 | awk -F"-" '{print $1}' | while read day file ; do mkdir -p "$day"; mv "$file" "$day"; done
It makes folder but not move
Upvotes: 0
Views: 95
Reputation: 1662
You can use xargs to achieve this.
ls *.mp4 | xargs -I{} sh -c 'folder=`echo {} | cut -d"-" -f1`;mkdir -p $folder;mv {} $folder/'
Here, the entire file names are sent to xargs
and, for each file the folder name is obtained using the cut
command. Then the file is moved into the created folder.
More about xargs: http://man7.org/linux/man-pages/man1/xargs.1.html
Edited
for file in *.mp4 ; do
date=$(echo $file | cut -d'_' -f1)
year=$(echo $date | cut -d'-' -f1)
month=$(echo $date | cut -d'-' -f2)
day=$(echo $date | cut -d'-' -f3)
mkdir -p $year/$month/$day
mv $file $year/$month/$day/
done
Upvotes: 1
Reputation: 15418
Aren't you getting errors? When I run it I get
mv: cannot stat '': No such file or directory
once for each file. The reason is that file
isn't being set in your loop.
ls *.mp4 | awk -F"-" '{print $1}'
Will generate a list of years
2018
2018
2019
2019
2019
2019
2019
2019
2019
That's a single column of data.
while read day file
reads the year into day
(day?) and since there's no more data, leaves file
empty.
mkdir -p "$day"
works fine, but
mv "$file" "$day"
evaluates to
mv "" "2018"
Try this.
for f in *.mp4
do mkdir -p "${f%%-*}" && mv "$f" "${f%%-*}"
done
The ${f%%-*}
just returns $f
with everything from the first dash removed. The result:
$: find
.
./2018
./2018/2018-12-09_19-50-59_UTC.mp4
./2018/2018-12-24_13-00-32_UTC.mp4
./2019
./2019/2019-01-03_14-45-43_UTC.mp4
./2019/2019-01-06_16-41-54_UTC.mp4
./2019/2019-01-11_14-51-08_UTC.mp4
./2019/2019-01-11_15-00-29_UTC.mp4
./2019/2019-02-03_10-33-33_UTC.mp4
./2019/2019-02-10_17-42-18_UTC.mp4
./2019/2019-02-16_18-21-30_UTC.mp4
Upvotes: 2