Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
55
Help us understand the problem. What is going on with this article?
@sand_bash

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

More than 5 years have passed since last update.

インフラエンジニアの方なら、調査の時に下記のような感じで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って高機能で本当に奥が深い。
他にも便利な機能あると思うので、また知ったら書くようにしよう。

55
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
55
Help us understand the problem. What is going on with this article?