1
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.

シェルスクリプトで特定の列を抽出する

Last updated at Posted at 2020-09-26

【追記】もっと良い方法があったらコメントお願いします。

列を抽出する

こういうファイルがあるとする。

abc.txt
aa bb cc dd ee ff
gg hh ii jj kk ll
mm nn oo pp qq rr
ss tt uu vv ww xx

そのうちn列目だけを取り出したいときの方法をまとめてみる。今回は3列目を取り出してみる。

awk

今まではこれしか知らなかった。速度が遅くて悩んだのが今回調べるに至った動機。

cat ./abc.txt | awk '{print $3}'

cut

さっき知った方法

cat ./abc.txt | cut -d ' ' -f 3

while

1行ずつ取り出して配列に変換して取り出す。正直めんどいし遅そう

while read line; do
    _line=(${line})
    echo "${_line[2]}"
done < ./abc.txt

余談

自分はいつもgetclmという関数を作成している。引数で列を指定し、テキストの内容は標準入力から受け取る。

function getclm() {
    echo "$(cat -)" | cut -d " " -f "${1}"
}

上の例の場合はこういうふうに使う。

cat ./abc.txt | getclm 3
1
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
1
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?