0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[awk]HTTPヘッダーのGMTのDateの整形

Last updated at Posted at 2021-06-11
  • HTTPでのリクエストやレスポンスを確認する手段としてのヘッダーは、厳格に表示仕様が決まっている。
  • その中で**If-Modified-Since(リクエスト)やLast-Modified(レスポンス)**といったようなDate、いわゆる日時は以下のような形式で表される。
    • 形式 : <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
    • 例 : Mon, 01 Feb 2021 11:15:07 GMT
  • 今回はこのようなGMT(グリニッジ標準時)での形式をawkで見やすい時刻へ整形する方法を記録する。

環境

  • Mac OS X 10.15.6

結果

  • 結果の記述は以下の通り。
main.awk
BEGIN{ print time_from_gmt(ARGV[1]) }

# 変換関数
function time_from_gmt(g){
	if(g==""){
		error("対象時刻を指定してください。")
	}
    # 月の対応表の作成
	count=split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",m," ")
	for(i=1;i<=count;i++){
		ma[m[i]]=i
	}
    # 対象時刻の正規化
	gsub(/:|,/,"",g)
	split(g,ga," ")
	time=sprintf("%04d%02d%02d%06d",ga[4],ma[ga[3]],ga[2],ga[5])
	return time
}

# error message
function error(m){
	print(m) > "/dev/stderr"
	exit(1)
}
  • 表示結果は以下。
$ awk -f main.awk "Mon, 01 Feb 2021 11:15:07 GMT"

# 年(4桁)月(2桁)日(2桁)時(2桁)分(2桁)秒(2桁)
20210201111507

内容

月の対応表の作成

  • HTTPヘッダーのDateでの月の表示は数字ではなくEnglish(先頭3語)となっているため、月名と数値の対応表を作る必要がある。
  • 月名をkeyにした連想配列にするため、splitで一度数値をkeyにした中間配列を作成した後に反転した新規の配列を作成する必要がある。
    • ※awkでの配列は全て連想配列である。

対象時刻の正規化

  • 引数として渡ってくるDateから不要なものを不要な文字や記号(コロンやカンマ)を取り除く。
  • またここでもsplitで連想配列化しておくことで、個々として扱うことが容易になる。
  • 表示形式を以下にしておくことで、各JSTやUTCへの変換分析の際のソート処理をする際にも便利。

まとめ

  • 一度awkやshellに定義しておくことで、以下のような用途の際に便利であると感じた。
    • curlでの最終更新時刻の取得及びこれを利用した判断ロジック
    • RSSにて提供される<pubDate>型の時刻の整形及びこれを利用したソート処理
  • また上記のことから最低限の機能を利用した処理の重要性を再認識した。

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?