LoginSignup
0
0

More than 5 years have passed since last update.

awk 使い方 (メモ)

Last updated at Posted at 2017-12-12

一覧

[root@localhost order]# awk '{ print }' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin


変数 $0 は現在行全体を意味するので、print と print $0 はまったく同じ動作となります。

[root@localhost order]# awk '{ print $0 }' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin


このスクリプトを実行すると、画面が test で埋まります。

[root@localhost order]# awk '{ print "test" }' /etc/passwd
test
test
test
test
test


awk は、複数の論理フィールドに分割されたテキストの処理が得意であり、awk のスクリプトの中から各フィールドを容易に参照することができます。次のスクリプトは、使用中のシステムに存在するユーザー・アカウントの一覧表を出力します。

[root@localhost order]# awk -F":" '{ print \$1 }' /etc/passwd
root
bin
daemon
adm
lp


上の例では -F オプションを使用して、”:” をフィールド区切り文字に指定しています。awk が print \$1 コマンドを実行すると、入力ファイルの各行の 1 番目のフィールドが出力されます。別の例をもう 1 つ示します。

[root@localhost order]# awk -F":" '{ print \$1 $3 }' /etc/passwd
root0
bin1
daemon2
adm3
lp4


[root@localhost order]# awk -F":" '{ print $1 " " $3 }' /etc/passwd
root 0
bin 1
daemon 2
adm 3
lp 4


substr使い方

[root@localhost order]# echo 'abcde' | awk '{print substr(\$0, 2, 3)}'
bcd
[root@localhost order]#
[root@localhost order]#
[root@localhost order]# echo 'abcde' | awk '{print substr(\$0, 1, 3)}'
abc
[root@localhost order]#
[root@localhost order]#
[root@localhost order]# echo 'abcde' | awk '{print substr($0, 1, 4)}'
abcd

sub使い方

[root@localhost order]# echo 'abc de' | awk '{sub(/ .*$/, ""); print}'
abc

if文みたいなもの

縦棒(|)がある場合、下の処理を実行
/|/{

縦棒(|)と7002の場合、下の処理を実行
\$0 ~ /|/ && $0 ~ /7002/{

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