1
3

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.

シェルスクリプトでCSVファイルを1行ずつ読み込んで処理する

Posted at

実現したいこと

・シェルスクリプトでCSVファイルを1行ずつ読み込む
・各行のカラムを取り出して処理する
・処理結果を別のCSVファイルとして出力する

具体的な要件

・以下のようなCSVファイル(input.csv)を読み込む

1,hoge,hoge,unko
2,hoge,hoge,hoge
3,hoge,hoge,hoge
4,hoge,hoge,unko
5,hoge,hoge,hoge
6,hoge,hoge,hoge
7,hoge,hoge,unko
8,hoge,hoge,hoge
9,hoge,hoge,hoge
10,hoge,hoge,unko

・4カラム目が「unko」である行のみ取り出し、別ファイル(output.csv)に出力する

実装例


# !/bin/bash

INPUTFILE="/tmp/input.csv"
OUTPUTFILE="/tmp/output.csv"

# ファイルを読み込む
while read -r LINE
do
  # 読み込み行の4カラム目の値を取り出す
  FOURTHCOLUMN=$(echo "${LINE}" | cut -d ',' -f4)

  # カラムの値が「unko」である場合、出力ファイルに書き込む
  if [ "${FOURTHCOLUMN}" = "unko" ]; then
    echo "${LINE}" >> "${OUTPUTFILE}"
  fi
done < "${INPUTFILE}"

このスクリプトを実行すると以下の出力ファイルが得られます。

output.csv
1,hoge,hoge,unko
4,hoge,hoge,unko
7,hoge,hoge,unko
10,hoge,hoge,unko
1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?