【问题标题】:Delete files older than x days on hadoop在 hadoop 上删除超过 x 天的文件
【发布时间】:2016-07-28 16:17:26
【问题描述】:

我正在构建一个 bash 脚本,用于删除指定目录中超过 x 天的日志文件。如您所知,hadoop fs 上没有“find”,所以我在 ruby​​ 中找到了一种巧妙的方法,想知道是否有办法在 bash 中实现。

在 Ruby 中:

#!/usr/bin/env ruby 
require "date"

five_days_ago = Date.parse(Time.now.to_s) - 5
IO.popen("hadoop fs -lsr /tmp").each_line do |line|  
  permissions,replication,user,group,size,mod_date,mod_time,path = *line.split(/\s+/)
  if (mod_date)
    if Date.parse(mod_date.to_s) < five_days_ago
      puts line
      if permissions.split('')[0] == 'd'
        puts "deleting #{path}"
        `hadoop fs -rmr -skipTrash #{path}`
        dirname = path
        next
      end 
      next if path.start_with? dirname
      `hadoop fs -rm -skipTrash #{path}`
    end
  end
end

【问题讨论】:

    标签: ruby bash hadoop fs


    【解决方案1】:

    这是我在bash中使用的,你可以试试:

    例如grep 所有 8 个月大的文件。根据需要更改 grep 正则表达式模式:

    hadoop fs -ls -R <location> | grep '.*2016-[0-8].*' | awk '{print $8}'
    

    删除文件:

    hadoop fs -rm -r `hadoop fs -ls -R <location> | grep '.*2016-[0-8].*' | awk '{print $8}'`
    

    【讨论】:

      【解决方案2】:

      我想通了。我知道有些人不建议使用 ls 来解决这类问题,但我正在使用 grep -o 来创建一个新行(所以我会知道会出现什么字符串)并且我知道文件名模式是这样,这将完美地工作。

      #!/bin/bash
      IFS=$'\n'
      source_path='/user/'
      current_date=$(date +%Y-%m-%d)
      files_ls=$(hdfs dfs -ls "$source_path" | grep -o " 2[0-9]\{3\}-.*")
      
      for line in $files_ls; do
          last_mod=$(echo "$line" | grep -o "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}")
          file_path=$(echo "$line" | grep -o " /user/.*.log")
          time_diff="$(( ($(date --date="$current_date" +%s) - $(date --date="$last_mod" +%s) )/(60*60*24) ))"
          if [ "$time_diff" -ge "8" ]; then
              echo "hdfs dfs -rm -skipTrash$file_path"
          fi
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-02
        • 1970-01-01
        相关资源
        最近更新 更多