欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Unix/Linux 中shell命令 awk

发布时间:2024/1/1 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Unix/Linux 中shell命令 awk 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

shell命令awk使用例:

  • 通过脚本打印出系统当前内存使用的百分比:
  • #!/bin/bash [centos@centos shell]$ free -mtotal used free shared buff/cache available Mem: 1819 508 130 11 1180 1130 Swap: 2047 368 1679 [centos@centos shell]$ vim useCache.sh echo "此脚本可以用来cha看当前系tong 内存使用百分比" use=$(free -m | grep Mem: | awk '{print $3}') total=$(free -m | grep Mem: | awk '{print $2}') useper=$(expr $use \* 100 / $total) echo "系tong当前内存使用百分比wei : " echo ${useper}% [centos@centos shell]$ chmod +x useCache.sh [centos@centos shell]$ ./useCache.sh 此脚本可以用来cha看当前系tong 内存使用百分比 系tong当前内存使用百分比wei : 27% [centos@centos shell]$


  • 以空格为分隔,显示每行有多少字段
  • [centos@centos shell]$ vim file aaaaaaaa bbbbb ccccc dddddd eeeee fffffffbbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeeeccccccc bbbbbbb eeeeee hhhhhhhhheeeeee ffffffffffff [centos@centos shell]$ awk '{print NF}' file 6 0 5 0 4 0 3 0 2 0 1
  • 以空格为分隔,查看文件中字段数大于4的行
  • [centos@centos shell]$ awk 'NF>4 {print}' file aaaaaaaa bbbbb ccccc dddddd eeeee fffffff bbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeee [centos@centos shell]$
  • 显示每一行的行号
  • [centos@centos shell_study]$ awk '{print NR, $0}' file 1 aaaaaaaa bbbbb ccccc dddddd eeeee fffffff 2 3 bbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeee 4 5 ccccccc bbbbbbb eeeeee hhhhhhhhh 6 7 fffff hhhhhhh yyyyyyyy 8 9 eeeeee ffffff 10 11 ffffff [centos@centos shell_study]$ awk 'NR==5 {print}' file ccccccc bbbbbbb eeeeee hhhhhhhhh
  • 不显示第一行
  • [centos@centos shell_study]$ route -n | awk 'NR!=1{print}' Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.150.1 0.0.0.0 UG 100 0 0 ens33 192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0 192.168.150.0 0.0.0.0 255.255.255.0 U 100 0 0 ens33 [centos@centos shell_study]$ route -n | awk 'NR>1{print}' Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.150.1 0.0.0.0 UG 100 0 0 ens33 192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0 192.168.150.0 0.0.0.0 255.255.255.0 U 100 0 0 ens33
  • 匹配文件中包含 root 的行
  • [centos@centos shell_study]$ awk -F: '/root/' /etc/passwd root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin
  • 不匹配文件中包含 root 的行
  • [centos@centos shell_study]$ awk -F: '!/root/' /etc/passwd
  • 匹配文件中空行的行号
  • [centos@centos shell_study]$ awk '{if($0~/^$/)print NR}' file 2 4 6 8 10
  • 不匹配文件中包含 root 的行
  • [centos@centos shell_study]$ awk -F: '!/root/' /etc/passwd [centos@centos shell_study]$ awk -F: '{if($3>100)print "LARGE";else print "SMALL"}' /etc/passwd


    总结

    以上是生活随笔为你收集整理的Unix/Linux 中shell命令 awk的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。