Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

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 1 year has passed since last update.

Linuxシェルコマンドawk

Last updated at Posted at 2022-04-07

シェルコマンドawkの使用例:

1、現在のホストの指定されたネットワークカードのIPアドレスを取得します:

[root@centos centos]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.150.52  netmask 255.255.255.0  broadcast 192.168.150.255
        inet6 fe80::149a:d07c:4d0e:dce6  prefixlen 64  scopeid 0x20<link>
        ...................................................................
[root@centos centos]# ipaddr=$(ifconfig ens33 | grep "broadcast" | awk '{print $2}')
[root@centos centos]# echo $ipaddr
192.168.150.52
[root@centos centos]#

!!!ens33:ネットワークカードを指定する、 $2:位置パラメータによるawk検索、区切り文字としてスペースを使用します。

2、passwdで1000を超えるユーザーのユーザー名とログインシェルを印刷します

[root@centos centos]# tail -3 /etc/passwd
centos:x:1000:1000:centos:/home/centos:/bin/bash
swk:x:1001:1001::/home/swk:/bin/bash
zbj:x:1002:1002::/home/zbj:/bin/bash
[root@centos centos]# cat /etc/passwd | awk -F: '$3>=1000 {print $1 "\t" $7}'
nfsnobody       /sbin/nologin
centos  /bin/bash
swk     /bin/bash
zbj     /bin/bash

!!![-F:]:区切り文字としてコロンを使用し、条件付き判断と出力の間に一重引用符を使用します。 "\ t":タブ文字、区切り文字としてタブキー

3、 システムにログインできる一般ユーザーを印刷する

[root@centos centos]# cat /etc/passwd | awk -F: '$3>=1000 && $7=="/bin/bash" {print $1 "\t" $7}'
centos  /bin/bash
swk     /bin/bash
zbj     /bin/bash

ヒント:複数の条件でフィルタリングします。二重引用符付きの文字列、2つの等号 ==

5、 情報を印刷するときにヘッダーを追加する

[root@centos centos]# cat /etc/passwd | awk -F: 'BEGIN {print "NAME \t SHELL"} $3>=1000 && $7=="/bin/bash" {print $1 "\t" $7}'
NAME     SHELL
centos  /bin/bash
swk     /bin/bash
zbj     /bin/bash

ヒント:BEGIN は大文字にする必要があります


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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?