77
61

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 5 years have passed since last update.

awkで末尾から数えてn番目のフィールドを取り出す。

Last updated at Posted at 2016-02-08

インフラエンジニアの方なら、調査の時に下記のような感じでawk のprint文を使ってログファイルから必要なフィールドだけ取り出すことも多いと思う。

# awk '{print $1,$4,$5}' /var/log/httpd/access_log
46.161.9.4 [07/Feb/2016:03:55:32 +0900]
133.130.88.115 [07/Feb/2016:03:58:13 +0900]
142.54.169.164 [07/Feb/2016:04:06:17 +0900]
133.130.88.115 [07/Feb/2016:04:08:13 +0900]
133.130.88.115 [07/Feb/2016:04:18:14 +0900]
157.7.137.160 [07/Feb/2016:04:28:13 +0900]
133.130.88.115 [07/Feb/2016:04:28:13 +0900]
69.30.198.202 [07/Feb/2016:04:35:01 +0900]

たまに「一番後ろから数えてn番目の値を取りたいな」って時があると思うが、そんな時に便利なのがawkの組込変数NF。

$NFで末尾のフィールドだけ取り出す。

  • 凡例

awk '{print $NF}' <ファイル名>

例えばapacheのaccess_logの末尾のフィールドだけ取り出すならこんな感じ。

# awk '{print $NF}' /var/log/httpd/access_log 
Safari/537.36"
2.0.3)"
6.0)"
2.0.3)"
2.0.3)"
2.0.3)"
+http://www.baidu.com/search/spider.html)"
+http://www.baidu.com/search/spider.html)"
2.0.3)"
# 

末尾から数えてn番目のフィールドだけ取り出す。

  • 凡例

awk '{print $(NF-n)}' <ファイル名>

例えばapacheのaccess_logの末尾から3番目、2番目、末尾のフィールドだけ取り出すならこんな感じ。


# awk '{print $(NF-3),$(NF-2),$(NF -1)}' /var/log/httpd/access_log
like Gecko) Chrome/27.0.1453.93
"-" "check_http/v2.0.3 (nagios-plugins
Media Center PC
"-" "check_http/v2.0.3 (nagios-plugins
"-" "check_http/v2.0.3 (nagios-plugins
- "-" "WordPress/4.4.2;
"-" "check_http/v2.0.3 (nagios-plugins
"Mozilla/5.0 (compatible; MJ12bot/v1.4.5;
"Mozilla/5.0 (compatible; MJ12bot/v1.4.5;
"Mozilla/5.0 (compatible; MJ12bot/v1.4.5;
#

awkって高機能で本当に奥が深い。
他にも便利な機能あると思うので、また知ったら書くようにしよう。

77
61
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
77
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?