如何从包含日期的多个文件中提取日期?

时间:2017-11-30 12:48:14

标签: linux bash shell

假设我有多个文件名,例如R014-20171109-1159.log.20171109_1159。 我想创建一个shell脚本,它为每个给定日期创建一个文件夹,并将与日期匹配的文件移动到它。 这可能吗?

例如,应创建一个文件夹“20171109”并在其上放置文件“R014-20171109-1159.log.20171109_1159”。

由于

4 个答案:

答案 0 :(得分:0)

下面的命令可以放在脚本中来实现这个目的,

使用下面的当前日期分配变量(如果需要更旧的日期,请使用 - date ='n day ago' 选项。)

如果需要从文件名本身获取它,在循环中获取文件然后使用 cut 命令获取日期字符串,

dirVar=$(date +%Y%m%d) --> for current day,

dirVar=$(date +%Y%m%d --date='1 day ago') --> for yesterday,

dirVar=$(echo $fileName | cut -c6-13)   or
dirVar=$(echo $fileName | cut -d- -f2) --> to get from $fileName

使用如下变量值创建目录,( -p :如果不存在则创建目录。)

mkdir -p ${dirVar}

将文件移动到目录下面的行目录

mv *log.${dirVar}* ${dirVar}/

答案 1 :(得分:0)

由于您要编写shell脚本,请使用命令。要获取日期,请使用cut cmd,例如ex:

cat 1.txt 
R014-20171109-1159.log.20171109_1159
 cat 1.txt | cut -d "-" -f2

输出

20171109 

是您的日期和创建文件夹。这样您就可以循环并创建任意数量的文件夹

答案 2 :(得分:0)

它实际上非常简单(我的Bash语法可能有点过时) -

for f in /path/to/your/files*; do

## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo $f > #grep the file name for "*.log." 
#and extract 8 charecters after "*.log." .
#Next check if a folder exists already with the name of 8 charecters. 
#If not { create}
#else just move the file to that folder path

break
done

主要观点来自这篇文章link。很抱歉没有提供实际代码,因为我最近在Bash上没有工作

答案 3 :(得分:0)

这是bash中for-loop的典型应用程序,用于迭代文件。 同时,此解决方案使用GNU [ shell param substitution ]

for file in /path/to/files/*\.log\.*
do

  foldername=${file#*-}
  foldername=${foldername%%-*}
  mkdir -p "${foldername}" # -p suppress errors if folder already exists
  [ $? -eq 0 ] && mv "${file}" "${foldername}" # check last cmd status and move

done
相关问题