0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ダウンロードしたCSVファイルの自動文字化け対策ツールを作ってみた。

Last updated at Posted at 2024-10-10

概要

MySQLWorkbenchでCSVファイルをダウンロードすると、文字コードがBOM無しのUTF-8のため、エクセルで開いたときに文字化けしてしまうことがあります。
ダウンロードしたCSVファイルの文字コードを自動でBOMを付けるツールを作成しました。

ツール作成方法

  1. fswatchコマンドをインストール

    brew install fswatch
    
  2. 下記のファイルを作成

    watch_csv.sh
    #!/bin/bash
    
    file_name=""
    
    # スクリプトのプロセスが既に実行中かどうかを確認
    if pgrep -f "$(basename "$0")" > /dev/null 2>&1; then
        exit 1
    fi
    
    # ~/Downloads フォルダを監視
    fswatch ~/Downloads | while read event; do
        # 最新のCSVファイルを取得
        new_file=$(find ~/Downloads -type f -name "*.csv" -print0 | xargs -0 ls -t | head -n 1)
    
        # 前回処理したファイルと同じ場合、スキップ
        [[ "$new_file" == "$file_name" ]] && continue
    
        # CSVファイルをUTF-8-BOMに変換
        nkf --overwrite --oc=UTF-8-BOM "$new_file"
    
        # 処理済みのファイル名を保存
        file_name="$new_file"
    done
    
    
  3. zshrcにコマンドを追加

    vi ~/.zshrc
    
    .zshrc
    bash ~/watch_csv.sh &
    

補足

  • fswatchコマンド
    fswatchread eventは、ファイルが追加、編集された際にスクリプトを実行します。ファイルが編集された場合にもイベントを検知してしまうため、スクリプト内では、すでに処理済みのファイルが再度実行されないよう工夫しています。

  • findxargsの連携
    findで指定したフォルダ内のCSVファイルをリストアップし、xargsでその結果をlsに渡して最新のファイルを取得しています。

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?