精简的Shell
cat /home/sev7e0/access.log | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'#cat 命令一次性展示出文本内容#tr -s ' ' '\n' 将文本中空格使用回车键替换#sort 串联排序所有指定文件并将结果写到标准输出。#uniq -c 从输入文件或者标准输入中筛选相邻的匹配行并写入到输出文件或标准输出,-c 在每行前加上表示相应行目出现次数的前缀编号#sort | uniq -c 同时使用用来统计出现的次数#sort -r 把结果逆序排列#awk '{print $2,$1}' 将结果输出,文本在前,计数在后
Scala
import scala.io.Source._val file = fromFile("/home/hadoopadmin/test.txt")val map = file.getLines().toList.flatMap(_.split(" ")).map((_,1)).groupBy(_._1)val value = map.mapValues(_.size)value.foreach(println(_))
反人类的MapReduce
//mapreduce方式public static void main(String[] args) throws Exception { Configuration conf = new Configuration();// conf.set("fs.defaultFS", "hdfs://spark01:9000");// conf.set("yarn.resourcemanager.hostname", "spark01"); Path out = new Path(args[1]); FileSystem fs = FileSystem.get(conf); //判断输出路径是否存在,当路径存在时mapreduce会报错 if (fs.exists(out)) { fs.delete(out, true); System.out.println("ouput is exit will delete"); } // 创建任务 Job job = Job.getInstance(conf, "wordcountDemo"); // 设置job的主类 job.setJarByClass(WordCount.class); // 主类 // 设置作业的输入路径 FileInputFormat.setInputPaths(job, new Path(args[0])); //设置map的相关参数 job.setMapperClass(WordCountMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); //设置reduce相关参数 job.setReducerClass(WordCountReduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); //设置作业的输出路径 FileOutputFormat.setOutputPath(job, out); job.setNumReduceTasks(2); System.exit(job.waitForCompletion(true) ? 0 : 1);}
好用的spark
//spark版wordcountsc.textFile("/home/sev7e0/access.log").flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).foreach(println(_))