【问题标题】:Get first and last files per month每月获取第一个和最后一个文件
【发布时间】:2012-04-23 05:21:33
【问题描述】:

基于这个问题Group files and pipe to awk command

我有一组这样的文件:-

-rw-r--r-- 1 root root 497186 Apr 21 13:17 2012_03_25
-rw-r--r-- 1 root root 490558 Apr 21 13:17 2012_03_26
-rw-r--r-- 1 root root 488797 Apr 21 13:17 2012_03_27
-rw-r--r-- 1 root root 316290 Apr 21 13:17 2012_03_28
-rw-r--r-- 1 root root 490081 Apr 21 13:17 2012_03_29
-rw-r--r-- 1 root root 486621 Apr 21 13:17 2012_03_30
-rw-r--r-- 1 root root 490904 Apr 21 13:17 2012_03_31
-rw-r--r-- 1 root root 491788 Apr 21 13:17 2012_04_01
-rw-r--r-- 1 root root 488630 Apr 21 13:17 2012_04_02

根据链接问题中的答案,我有一个包含以下代码的脚本,可以正常工作:-

DIR="/tmp/tmp"
for month in $(find "$DIR" -maxdepth 1 -type f | sed 's/.*\/\([0-9]\{4\}_[0-9]\{2\}\).*/\1/' | sort -u); do
  echo "Start awk command for files $month"
  power=$(awk -F, '{ x += $1 } END { print x/NR }' "$DIR/${month}"_[0-3][0-9])
  echo $power
done

下面的命令本身会返回一个这样的列表:-

find /tmp/tmp -maxdepth 1 -type f | sed 's/.*\/\([0-9]\{4\}_[0-9]\{2\}\).*/\1/' | sort -u

2011_05
2011_06
2011_07
2011_08
2011_09
2011_10
2011_11
2011_12
2012_01
2012_02
2012_03
2012_04

find 命令使用 GLOB 将一组文件传递给 AWK 以作为批处理进行处理。

基于此,我希望能够运行以下剪切命令

head -1 FirstFile | date -d "`cut -d, -f7`" +%s

tail -1 LastFile | date -d "`cut -d, -f7`" +%s

这些需要为 FIRST 和 LAST 文件 PER SET 运行

因此,对于上面的 2012_03,需要为 2012_03_25 文件运行头部,而对于 2012_03_31 需要运行尾部,因为这些是 3 月份集合中的第一个和最后一个文件。

所以基本上我需要能够获得每批的第一个和最后一个文件。

我希望我已经说得够清楚了,如果不是请发表评论。

【问题讨论】:

    标签: linux bash sed awk


    【解决方案1】:
    DIR="/tmp/tmp"
    for month in $(find "$DIR" -maxdepth 1 -type f | sed 's/.*\/\([0-9]\{4\}_[0-9]\{2\}\).*/\1/' | sort -u); do
          echo "Start awk command for files $month"
          IFS=, read start end power < <(awk -F, 'BEGIN{OFS = ","} NR == 1 {printf "%s,", $7} { x += $1; d = $7 } END { print d, x/NR }' "$DIR/${month}"_[0-3][0-9])
          echo $power
          date -d "$start" +%s
          date -d "$end" +%s
    done
    

    这里是使用 here-doc 的方法,它应该适用于大多数 shell:

          read start end power <<EOF
    $(awk -F, 'NR == 1 {printf "%s ", $7} { x += $1; d = $7 } END { print d, x/NR }' "$DIR/${month}"_[0-3][0-9]))
    EOF
    

    【讨论】:

    • 我喜欢这个解决方案,但是在使用
    • @generalexception:什么外壳?我假设它不是 Bash、ksh 或 zsh,以便给你一个错误。您可以尝试&lt;&lt;&lt; $()(此处为带有命令替换的字符串),但如果进程替换不起作用,则可能会失败。您也可以尝试使用 here-doc。有关示例,请参阅我编辑的答案。
    • 它不是外壳,因为 awk 命令将日期作为 YYYY/MM/DD HH:MM:SS 格式的字符串返回,它将 YYYY/MM/DD 分配给 $start, HH :MM:SS 到 $end 和下一个 YYYY/MM/DD 到 $power。日期中的空格导致问题。
    • @generalexception:哦,我没有考虑到-F,。尝试我的下一个编辑。
    • 嗯,在命令行上工作,当我将它放入 MyScript.sh 文件时,它在该行上给我一个重定向意外错误。 $SHELL 是 /bin/bash
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多