天天看點

doy 17 例題

# 例題

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][email protected]" 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

繼續閱讀