LoginSignup
1
1

More than 5 years have passed since last update.

CSVファイルから特定の列を取り出す自作関数

Last updated at Posted at 2016-06-25

シェルで作業している時に、スペース区切りやTSVファイルから特定の列を取り出したいことがある。

cutコマンドは便利だが、区切り文字に単一の文字しか使えない、デフォルトではスペースではなくタブ、など少し使いにくい。

で、結局awkコマンドを使うことになるが、cutよりも小指が疲れる上、タイプ量が増えてしまう。

cat <<EOF > test.txt
a b c
d e f
EOF

# cutを使う場合
cat test.txt | cut -d ' ' -f 1,3
#=> a c
#=> d f

# awkで同じことをする
cat test.txt | awk '{print $1, $3}'
#=> a c
#=> d f

そこで、極力少ないタイプ量で処理できる自作関数colprintを作った。

colprint(){
    options=''
    while getopts F: OPT; do
        options="$options -$OPT $OPTARG"
    done

    shift $((OPTIND - 1))

    command=''
    for str in $@; do
        command=`echo $command '$'$str, `
    done

    awk $options "{print `echo $command | sed 's/,$//g'`}"
}

使い方はこんな感じだ。

cat <<EOF | colprint 1 3
a b c
d e f
EOF
#=> a c
#=> d f

cat <<EOF | colprint -F ,, 1 3
a,,b,,c
d,,e,,f
EOF
#=> a c
#=> d f

参考URL http://qiita.com/b4b4r07/items/dcd6be0bb9c9185475bb

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