シェルで作業している時に、スペース区切りや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