標籤:學習隨筆
grep [acivn] [--color=auto] ‘尋找字串‘ filename
-a:將binary檔案以text檔案的方式尋找資料
-c:計算找到‘尋找字串‘的次數
-i:忽略大小寫
-v:反向選擇
-n:將尋找結果列出行號
--color=auto:尋找結果中關鍵字著色
**********grep使用例子**********
(1)列出一個目錄下目錄的名稱:
ll |grep ‘^d‘ |awk ‘{print $9}‘
其中awk中$後面是列的位置
(2)列出一個檔案,去除空白行:
grep -v ‘^$‘ /etc/httpd/conf/httpd.conf
(3)去除注釋行
grep -v ‘^$‘ /etc/httpd/conf/httpd.conf |grep -v ‘^#‘
(4)忽略大小寫並註明行號:
dmesg |grep -in ‘network‘
(5)尋找一個以m開頭、並且以m結尾的單詞
grep -in ‘m[a-z]*m‘ regular_express.txt
**********Regex基礎**********
--word 字串
--char 字元
--list字元序列
^word表示以word開頭
word$ 表示以word結尾
.表示一定有一個任一字元
char*表示有0個或無窮多個重複的char
\逸出字元
[list]表示選擇一個字元匹配,例如a[bc]a 表示aba & aca
[char1-char2]表示任意的連續字元,char1到char2之間,例如[a-z]表示任意小寫字母
[^list]表示去除不要的字元,有反向選擇的意思,例如[^abc] 表示去除包含abc串的行
char\{n,m\}表示n到m個char,需要使用逸出字元
eg:一個指令碼,類比service httpd status 輸出
#!/bin/bash#The output of commond "service httpd status" or "/etc/init.d/httpd status"m=$(ps -ef |grep httpd |sed ‘s/^.*grep.*$//g‘ |sed ‘/^$/d‘)n=$(ps -ef |grep httpd |sed ‘s/^.*grep.*$//g‘ |sed ‘/^$/d‘ |grep root |grep /usr/sbin/httpd |awk ‘{print $2}‘)#n=$(ps -ef |grep httpd |grep -v grep |grep root |grep /usr/sbin/httpd |awk ‘{print $2}‘)#n=$(ps -ef |grep httpd |sed ‘/.*grep.*/d‘ |grep root |grep /usr/sbin/httpd |awk ‘{print $2}‘)if [ "$m" = "" ];then echo "httpd is stopped"else echo "httpd (pid "$n") is running..."fi
本文出自 “小菜鳥” 部落格,請務必保留此出處http://akiny09.blog.51cto.com/1299657/1429980