grep及Regex隨筆

來源:互聯網
上載者:User

標籤:學習隨筆

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.