刪掉檔案的第一行(常用來去掉標題列):
sed '1d' filename
取出每一列的最後一個欄位:
awk '{print $NF}' filename
comm -3 --nocheck-order file1 file2 grep -v -f file1 file2 # 列出 file2 有、file1 沒有的行 diff file1 file2
三者取向不同:comm 適合已排序的清單,grep -v -f 做集合差集很俐落,diff 則保留逐行異同的細節。
下面是一段把上述技巧串起來的腳本,用 Hadoop 列出昨天與今天的日誌目錄,去掉表頭、取出路徑欄位,再差集出「今天才出現」的清單:
#!/bin/bash
date_time=`date +'%H_%M_%S'`
yesterday=`date -d"-1 day" +'%Y_%m_%d'`
today=`date +'%Y_%m_%d'`
date_day_time=`date +'%Y_%m_%d_%H_%M_%S'`
BASE=/home/spamdetect/changxiaojia/workspace/finance/same_similar_news_mining
mkdir $BASE/same_similiar_log/$today
yesterday_input=/home/crawler/petabyte/crawllog/news_data/$yesterday
today_input=/home/crawler/petabyte/crawllog/news_data/$today
/opt/hadoop/program/bin/hadoop fs -ls $yesterday_input/ > $BASE/mid_files/all_get
/opt/hadoop/program/bin/hadoop fs -ls $today_input/ >> $BASE/mid_files/all_get
sed '1d' $BASE/mid_files/all_get > $BASE/mid_files/all_get_without_first_line
awk '{print $NF}' $BASE/mid_files/all_get_without_first_line > $BASE/mid_files/all_input
grep -v -f $BASE/mid_files/input_done $BASE/mid_files/all_input > $BASE/mid_files/today_diff
awk '{print $NF}' $BASE/mid_files/today_diff > $BASE/mid_files/today_new_input
mv $BASE/mid_files/all_input $BASE/mid_files/input_done
inputfile1=""
while read line
do
inputfile1=$inputfile1,${line}
done < $BASE/mid_files/input_done
echo $inputfile1
腳本裡我把冗長的絕對路徑抽成 BASE 變數,可讀性會好很多;最後的 while 迴圈則是把清單拼成以逗號分隔的單一字串,方便餵給後續的 MapReduce 程式當輸入。