加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

grep及正则表达式随笔

发布时间:2020-12-14 01:43:44 所属栏目:百科 来源:网络整理
导读:grep [acivn] [--color=auto] '查找字符串' filename -a:将binary文件以text文件的方式查找数据 -c:计算找到'查找字符串'的次数 -i:忽略大小写 -v:反向选择 -n:将查找结果列出行号 --color=auto:查找结果中关键字着色 **********grep使用例子*********

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


**********正则表达式基础**********

--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
#Theoutputofcommond"servicehttpdstatus"or"/etc/init.d/httpdstatus"

m=$(ps-ef|grephttpd|sed's/^.*grep.*$//g'|sed'/^$/d')
n=$(ps-ef|grephttpd|sed's/^.*grep.*$//g'|sed'/^$/d'|greproot|grep/usr/sbin/httpd|awk'{print$2}')
#n=$(ps-ef|grephttpd|grep-vgrep|greproot|grep/usr/sbin/httpd|awk'{print$2}')
#n=$(ps-ef|grephttpd|sed'/.*grep.*/d'|greproot|grep/usr/sbin/httpd|awk'{print$2}')
if["$m"=""];
then
echo"httpdisstopped"
else
echo"httpd(pid"$n")isrunning..."
fi

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读