一、grep
grep -E = egrep
grep命令的格式
grep 匹配条件 处理文件
grep root /etc/passwd
: 过滤/etc/passwd文件中含有root关键字的行
grep ^root /etc/passwd
:过滤/etc/passwd文件中以root为开头的行
grep halt$ file1
:过滤/etc/passwd文件中以root为结尾的行
grep -i root file1
: 忽略大小写
grep -E “\<root” file1
:root字符之前不能有字符
```grep -E “root>” file1`` :root字符之后不能有字符
grep -数字:显示过滤行和其上下几行的内容
grep -A 数字:显示过滤行和其下面几行的内容
grep -B 数字:显示过滤行和其上面几行的内容
grep -n:显示过滤行所在行号
grep -v:反向过滤
grep字符数量匹配规则
^westos :以westos开头
westos$:以westos结尾
w…s:w开头s结尾中间四个字符任意
…s:s结尾前面五个任意字符
*:字符出现任意
?:0到1次
+:一次到任意次
{n}:n次
{m,n}:m到n次
{0,n}:0-n次
{,n}:0-n次
{m,}:最少m次
(ws){n}:ws字符串出现n次
二、sed
sed的命令格式:
sed 参数 命令 处理对象
sed 参数 处理对象 -f 处理规则文件
对字符的处理
p:显示
sed -n 5p file1
:显示第5行
sed -n 3,5p file1
:显示三到五行
sed -ne “3p;5p“ file1
:显示三和五行
sed -ne 1,5p file1
:显示1-5行
sed -ne '5,$p' file1
:显示5到最后一行
sed -n '/^#/p' /etcfstab
:显示#开头的行
d:删除
sed 5d file:删除第五行
sed '/^#/d' /etc/fstab
:删除#开头的行
ed '/^UUID/!d' /etc/fstab
:删除UUID以外的行
sed -e '5,$d' /etc/fstab
:删除5到最后一行
a:添加
sed -e '$a hello world' /etc/fstab
:在末行添加hello world
sed -e '$a hello\nworld' /etc/fstab
:在末行添加hello换行world
sed -e '/^#/a hello world' /etc/fstab
:在以#开头的行后添加hello world
c:替换
sed -e '/^#/c hello world' /etc/fstab
:把#开头的行内容替换为hello world
sed '3chello world' /etc/fstab
:把第三行内容替换为helloworld
i:插入
sed '3ihello westos' /etc/fstab
:给第三行前添加hello westos
r:整合文件
sed ‘5r haha’ westos
sed 字符替换
sed ‘s/:/###/g’ file
:将:换为###
sed ‘/s:/###/’ file
:将每行第一个:换成###
sed '1,5s/:/###/g' file
:将1到5行所有的:换成###
sed '1s/:/###/g' file
:将第一行的:换为###
sed '1s/:/###/;5s/:/###/g' file
:将第一行和第五行的:换为###
sed '/gdm/,/rngd/s/:/###/g' file
:将从gdm到rngd中间的:换为###
sed ‘/\//####/g’ file
:将(特殊字符后需加上/)换为####
sed 's@/@####@g' -i file
将修改过的内容存进文件file中(@相当于分割符/)
三、awk
awk -F 分隔符 BEGIN{ }{ }END{ } FILENAME
NR:行数
NF:列数
FILENAME:文件名称本身
westos:westos变量值
“westos”:westos字符串
/bash$/:条件
/条件1|条件2:条件1或者条件2
/条件1/||/条件2/:条件1或者条件2
/条件1/&&/条件2/:条件1并且条件2
$0:所有列
$1:第一列
$2:第二列
$3:第三列
四、练习脚本
1.请显示系统中能被su命令切换的用户名称
grep bash$ /etc/passwd | cut -d : -f 1
2.Apache_port.sh脚本后加入数字,http的端口就改为此数字,假设selinux为关闭状态
#!/bin/bash
[ -z "$*" ] && {
echo "请输出端口号"
exit
}
[ "$(id -u)" = "0" ] || {
echo "没有修改端口的权限"
exit
}
rpm -q httpd &> /dev/null || {
echo "Apache未安装"
exit
}
pidof httpd &> /dev/null || {
echo "httpd服务未启动"
exit
}
grep -E "\<Listen $*\>" /etc/httpd/conf/httpd.conf &> /dev/null && {
echo "该端口已被Apache使用"
exit
}
ss -antlpe | grep -E "\<$*\>" &>/dev/null && {
echo "该端口已被占用"
exit
}
sed -e "/^Listen/c Listen $*" -i /etc/httpd/conf/httpd.conf &> /dev/null
systemctl restart httpd