LoginSignup
55
57

More than 5 years have passed since last update.

awk のハマるポイントまとめ

Last updated at Posted at 2013-11-14

ダブルクォートではなくシングルクォートでくくること

ダブルクォートでくくると,シェルが引数と勘違いするので,シングルクォートでくくるかエスケープすること.

awk "{print $1}" /etc/hosts

awk '{print $1}' /etc/hosts
awk "{print \$1}" /etc/hosts

区切り文字を複数設定するとき

-Fオプションで,文字クラス指定できる.が,1字ずつで区切られてしまう.
そのため,*を必ずつけること.

awk -F '[= ]' '{print $1,$2}' /etc/sysctl.conf
awk -F "[= ]" '{print $1,$2}' /etc/sysctl.conf

awk -F '[= ]*' '{print $1,$2}' /etc/sysctl.conf
awk -F "[= ]*" '{print $1,$2}' /etc/sysctl.conf

ただ,この方法だと,先頭に空白がある場合に$1が空白になるので注意.
(方法知ってる方コメントお願いします.)

SSHコマンドでリモートホストにawkコマンドを流すとき

そのままだと$記号が有効にならないので,エスケープする.
(上記参考)

ssh hoge.com "awk '{print \$1}'"
ssh hoge.com 'awk "{print \$1}"'

awkはそれ単体だけでなく,grep等と組み合わせることが多いので,リモートに送るコマンドは(シングル or)ダブルクォートでくくっておく.
クォートがないとパイプ前の出力結果をローカルホストで受け取ることになり,NWに負担がかかる.

ssh hoge.com "grep POST /usr/local/apache/logs/access_log | awk '\$9 ~ /^50/ {print \$0}'"

EXITステータスはエラーにならない限りEXIT_SUCCESS

(2014/03/14追記)
grepとおなじ感覚で使ってて痛い目に合ったので。
参考:Exit Statement - The GNU Awk User's Guide

% cat <<EOS | grep hoge
aiueo
fuga
EOS
% echo $?
1

% cat <<EOS | awk '/hoge/{print $0}'
aiueo
fuga
EOS
% echo $?
0
55
57
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
55
57