[英]Bash: epoch time stored in variable pass into date command and make folder name
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;所需的 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.它创建
$name
文件夹,但不创建$hrdate
文件夹。 Tried several things with date like date -d
or unquoted $epoch
but I don't know what am I failing at.用
date -d
或未引用的$epoch
等日期尝试了几件事,但我不知道我在什么方面失败了。
EDIT: I made some changes to scripts upon #tripleee's answer编辑:我根据#tripleee 的回答对脚本进行了一些更改
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
There's a trailing space on the hrdate definition, it should be like this: hrdate 定义后面有一个空格,应该是这样的:
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 found from man
page to use --date
and added @
.我从
man
页中找到使用--date
并添加了@
。
hrdate=$(date +%F --date "@$epoch")
+%F
stands for YYYY-MM-DD format. +%F
代表 YYYY-MM-DD 格式。
This worked for me这对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.