LoginSignup
1
2

More than 5 years have passed since last update.

シェルスクリプトを用いたファイル出力

Posted at

よくある運用を想定した題材を通して、自動実行やシェルスクリプトを活用した運用の雰囲気やコマンドを駆使することで、出来ることの可能性について掴む。
コマンドを色々と覚えることで開発や運用の幅は格段に広がりそう。

RFP

毎月1日に日本郵便株式会社から自動で最新の郵便番号情報ファイル(沖縄県のみ)を取得して、
以下のフォーマットに加工してUTF-8でファイル出力せよ。
※課題なので月次ではなく、3分おきとか5分おきとかでやってみる

実装方法

シェルスクリプト(bash)を使用してデータを取得

<ファイルフォーマット>

  • 郵便番号
  • 都道府県名(漢字)
  • 市区町村名(漢字)
  • 町域名(漢字)

<使用コマンドヒント>

  • crontab - 自動実行
  • wget - ファイル取得
  • cut - データ分割
  • nkf - 文字コード変換
  • unzip - ファイル解凍

※vagrant環境で実行し、足りないコマンドはyum instal (コマンド名)でインストール

余裕があれば、DLデータの1列目の各市区町村コードに属する町域名の数をコマンドのみでファイル出力してみる。

(例)
件数<タブ>市区町村コード

79 47201
21 47205
23 47207
21 47208
55 47209

コマンド

▼シェルスクリプトでファイル取得からの保存(hoge.sh)

hoge.sh
#!/bin/sh
date=`date "+%Y%m%d"`
wget http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/47okinaw.zip
unzip 47okinaw.zip
cut -d , -f 3,7,8,9 47OKINAW.CSV | nkf -w >> ${date}_before47OKINAW.txt
cat ${date}_before47OKINAW.txt | tr -d '"' >> ${date}_47OKINAW.txt
rm ${date}_before* 47*

---- バーミッション変更する

chmod +x hoge.sh

---- 毎月1日の自動実行処理をcrontabに記載

crontab -e
0 0 1 * * /var/www/html/elites-test/bashtest/hoge.sh

▼特定フィールドの重複削除・件数確認

cut -d , -f 1 47OKINAW.CSV |nkf -w|uniq -c
1
2
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
1
2