# 例题

1、找出/proc/meminfo文件中以s开头的行,至少用三种方式忽略大小写

​ (1) [root@localhost ~ 14:27:39]#grep -iE '^s' /proc/meminfo

​ (2) grep -E '^[sS]' /proc/meminfo

​ (3) awk '/^[sS]/' /proc/meminfo

​ (4)sed -n -r '/^[sS]/p' /proc/meminfo

3、找出/etc/init.d/functions文件下包含小括号的行

​ grep -E '[()]' /etc/init.d/functions

4、输出指定目录的基名

​ pwd |awk -F/ '{print $NF}'

5、找出网卡信息中包含的数字

​ 1、cd /etc/sysconfig/network-scripts/

​ 2、ll

​ 3、 grep -oE '[0-9]+' /etc/sysconfig/network-scripts/ifcfg-*

6、找出/etc/passwd下每种解析器的用户个数

​ awk -F: '{arr[$NF]++}END{for(i in arr){printf "%-15s %s \n",i,arr[i]}}' /etc/passwd

7、过滤网卡中的ip,用三种方式实现

(1)ip a | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}'

​ (2)ip a | sed -rn '/([0-9]{1,3}\.){3}[0-9]{1,3}/p'

(3)ip a |awk '/([0-9]{1,3}\.){3}[0-9]{1,3}/{print $2,$4}'|awk '{if (NR==1){print $1}else {print $1,$2}}'

8、搜索/etc目录下,所有的.html或.php文件中包含的main函数出现的次数

​ (1)find /etc/ -name "*.html" -o -name "*.php" /etc

​ (2)grep -E 'main' $(find /etc/ -name "*.html" -o -name "*.php" ) |wc -l

9、过滤/etc/fstab中注释的行和空行

​ grep -vE '^$|^ *#' /etc/fatab

10、找出文件中至少有一个空格的行

​ grep -E " +" /etc/fatab

11、过滤文件中以#开头的行,后面至少有一个空格

​ grep -E "# +" /etc/fatab

12、查询出/etc目录中包含多少个root

​ egrep -oR 'root' /etc/ |wc -l

13、查询出所有的qq邮箱

​ egrep "[0-9a-zA-Z]+@qq.com" 1.txt

14、查询系统日志(/var/log/message)中所有的error

​ grep -iE 'error' /var/log/messages

16、删除一个文件中的所有数字

​ sed -r 's/[0-9]//g' 1.txt

17、显示奇数行

awk -F: 'NR%2{print $0}' 1.txt

18、删除passwd文件中以bin开头的行到nobody开头的行

sed -r "/^bin/,/^nobody/d" /etc/passwd

20、每隔5行打印一个空格行

​ 1、awk -F: '{if(NR%6){printf "\n%s",$0}else{print $0}}' /etc/passwd

(1)awk -F: '{if(NR%6==0){printf "%s\n\n",$0}else{print $0}}' /etc/passwd

21、不显示指定字符的行

grep -vE 'root' /etc/passwd

22、将文件中1到5行中aaa替换成AAA

sed -r '1,5s/aaa/AAA/g' 1.txt

23、显示用户id为奇数的行

awk -F:'{if($3%2){print $0}}' /etc/passwd

25、统计nginx日志中访问量(ip维度计算)

grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/nginx/access.log

26、统计nginx日志中的访问人数

(1) grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/nginx/access.log | awk'{arr[$0]++}END{print length(arr)}'

(2) grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/nginx/access.log |sort |uniq -c | wc -l

27、统计访问nginx前10的ip

grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/nginx/access.log |sort |uniq -c |sort -rn |head -10

知识储备 :

​ sort :处理排序 (默认第一数值排序)

​ -n :按照数值大小排序

​ -r :按照倒序排序

​ uniq :处理重复(只能够处理相邻的重复)

​ -c :打印出重复次数

head :从文本头部开始读数据(默认只读10行)

​ -n : 多少行

while 循环

​ while (判断条件){ }

案例一、把/etc/passwd中的每行打印三遍

awk -F: '{i=o;while(i<3){print $0;i++}}' /etc/passwd

案例二、统计/etc/passwd中的每个解析器的用户的元数

awk -F: '{arr[$NF]++}END{for(i in arr){print i,arr[i]}}' /etc/passwd

案例三、要求把/etc/passwd的第十行每一列分别打印出来

awk -F: 'NR==10{i=0;while(i<=NF){print $i;i++}}' /etc/passwd

 

posted on 2021-10-11 17:42  李辉111  阅读(41)  评论(0编辑  收藏  举报