0

I am writing a script that creates subfolders depending on epoch times included in file names. here is a sample filename;

movie_lotr_frodo_1608020500_1608020510

desired output;

frodo/2020-12-15/movie_lotr_frodo_1608020500_1608020510

here is my script;

dir="/root/user/test"
cd "$dir"

for x in *; do
    name=`echo $x | awk -F"_" '{print $3}'`
    epoch=`echo $x | awk -F"_" '{print $5}'`
    hrdate=$(date -r "$epoch" +%Y-%m-%d)
    mkdir -p "$name/$hrdate"
    mv -- "$x" "$name/$hrdate"
done

I get the error;

date: 1068020510: No such file or directory

It creates $name folders but not $hrdate folders. Tried several things with date like date -d or unquoted $epoch but I don't know what am I failing at.

EDIT: I made some changes to scripts upon #tripleee's answer

3 Answers3

2

Here's a refactored version with the following changes:

for x in ./*; do
    epoch=${x##*_}
    tail=${x%"_$epoch"}
    name=${tail%_*}
    hrdate=$(date -r "$epoch" +%Y-%m-%d)
    mkdir -p "$name/$hrdate"
    mv -- "$x" "$name/$hrdate"
done
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

There's a trailing space on the hrdate definition, it should be like this:

dir="/root/user/test"
cd "$dir"

for x in *; do
    name=`echo $x | awk -F"_" '{print $3}'`
    epoch=`echo $x | awk -F"_" '{print $5}'`
    hrdate=$(date -r "$epoch" +%Y-%m-%d)
    mkdir -p $name/$hrdate
    mv -- $x $name/$hrdate
done
Gabriel Pellegrino
  • 1,042
  • 1
  • 8
  • 17
0

I found from man page to use --date and added @.

hrdate=$(date +%F --date "@$epoch")

+%F stands for YYYY-MM-DD format.

This worked for me