« Linux BoxにTime Machineを使ってバックアップする方法 [UPDATE] | Home | JavaScriptでのクロージャーのテスト »

October 11, 2009

時系列データファイルから必要な時間のデータを取り出すスクリプト

久しぶりにshell (bash) script。一つのデータが一行ごとに並んでいるファイルから必要な部分を取り出すスクリプト。今回はbashの組み込み関数である getopts を使ってみた。

#!/bin/bash
#
# clip.sh -f FROM -t TO FILE
#

while getopts "f:t:" i;do
	case $i in
		f) FROM=$OPTARG;; # Time From
		t) TO=$OPTARG;;   # Time To
	esac
done

shift $(($OPTIND - 1))
FILE=$1

LINES=`wc --line $FILE | cut -d " " -f 1`
FLINE=`grep -n $FROM $FILE | cut -d : -f 1 | head -n 1`
TLINE=`grep -n $TO $FILE | cut -d : -f 1 | head -n 1`

if [ $FLINE -ge $TLINE ]; then
	TMP=$FLINE;
	FLINE=$TLINE;
	TLINE=$TMP;	
fi

HEAD=$(($TLINE-$FLINE))
TAIL=$(($LINES-$FLINE+1))

tail -n $TAIL $FILE | head -n $HEAD

 たとえばこのようなファイルがあるとすると

11:00:17 24.93 72.9
11:00:17 24.94 72.8
11:00:17 24.94 72.7
11:00:18 24.95 72.4
11:00:19 24.96 72.1
11:00:20 24.97 71.9
11:00:21 24.97 71.8
11:00:22 24.98 71.7
11:00:23 24.99 71.4
11:00:24 25.00 71.2
....

このファイルをdata.txtというファイル名として、この中から12:00:00から13:00:00まで取り出したいとすると、

$ clip.sh -f 12:00:00 -t 13:00:00 data.txt

とすれば標準出力に出力される。

 ふ、例によって誰もついて来れまい。あ、ぴらふとCZDの二氏は除く。ってかこのくらいのコマンドは、textutilあたりにありそう。良い解法があればコメントよろ。

No TrackBacks

TrackBack URL: http://www.argv.org/~chome/blog/mt-tb.cgi/194

About this Entry

This page contains a single entry by chomy published on October 11, 2009 2:05 AM.

Linux BoxにTime Machineを使ってバックアップする方法 [UPDATE] was the previous entry in this blog.

JavaScriptでのクロージャーのテスト is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.