shell命令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通过位置参数进行检索、以空格作为分隔符。

  1. 打印出 passwd 中用户大于 1000 的用户名和登录 shell
[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":制表符,Tab键作为分隔

  1. 打印出系统中能登录的普通用户
[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

提示 多条件进行过滤、字符串用双引号,两个等号 ==

  1. 打印输出信息时加上表头
[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 必须大写


GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:1 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐