Linux(23)—— shell [ grep sed awk ]
这几章笔记是针对redhat8系统中bash的操作指令做记录。
1. grep
用于使用匹配条件过滤指定文本。
[root@rhserver Desktop]# grep [options] files
grep root passwd #过滤root关键字
grep -i root passwd #忽略大小写
grep -数字 #显示过滤行以及上面几行和下面几行
grep -n #显示匹配的行所在行号
grep -A #显示过滤行以及下面几行
grep -B #显示过滤行以及上面几行
grep -v #反向过滤
grep -E #支持扩展匹配规则
匹配规则(部分需要指定扩展匹配 -E):
"\<root" #root字符之前不能有字符 (扩展)
"root\>" #root字符之后不能有字符 (扩展)
^root #以root开有 (扩展)
root$ #以roots结尾(扩展)
r....t #r开头t结尾中间4个任意字符
.....t #t结尾前面5个任意字符
* #指定字符出现任意
? #指定字符出现0到1次 (扩展)
+ #指定字符出现1次到任意次 (扩展)
{n} #指定字符出现n次(扩展)
{m,n} #指定字符出现m到n次(扩展)
{,n} #指定字符出现0-n次(扩展)
{m,} #指定字符出现最少m次(扩展)
(root){2} #root字符串出现2次(扩展)
练习:请显示系统中能被su命令切换的用户名称
2. sed
Linux sed 命令是利用脚本来处理文本文件。
sed 可依照脚本的指令来处理、编辑文本文件。
[root@rhserver Desktop]# sed [OPTIONS] [actions] [FILE]
OPTION | 含义 |
---|---|
-e | 指定Script处理文本文件 |
-f | 指定Script文件处理文本文件 |
-i | 将处理后的文本文件覆盖源文件 |
-n or --quie or --silent | 仅显示script处理后的结果 |
处理动作 | 含义 |
---|---|
a | 向指定行下一行后添加内容 |
i | 将内容插入至指定行 |
c | 取代,更改,可接字符 |
p | 显示 |
w | 写入指定文件(指定内容写入至w后接文件) |
r | 整合内容至文件(r后接文件内容插入至目标文件) |
####### 字符处理
sed -n 5p file1 #显示第5行
sed -n 3,5p file1 #显示3到5行
sed -ne "3p;5p" file1 #显示3和5行
sed -ne "1,5p" file1 #显示1-5行
sed -ne '5,$p' file1 #显示5到末尾
sed -n '/^#/p' file1 #显示以#开头的行
sed 5d file1 #删除第五行
sed '/^#/d' file1 #删除#开头的行
sed '/^UUID/!d' file1 #删除除了UUID以外开头的行
sed -e '5,$d' file1 #删除5到末尾
sed -e '$a hello\nworld' file1 #末尾插入hello (换行)world
sed -e '/^#/a hello world' file1 #以#开头的行尾插入hello world
sed -e '/^#/c hello world' file1 #以#开头的行更换为hello world
sed '5chello world' file1 #第五行更换为hello world
sed '5ihello ' file1 #在第五行插入 hello
sed '/^UUID/w file2' file1 #把file1中UUID开头的行写入file2中
sed '5r file2' file1 #将file2内容从file1第五行插入
####### 字符替换
sed 's/:/#/g' file1 #将file1所有行所有:都替换为#
sed 's/:/#/' file1 #将file1所有行的第1列:都替换为#
sed '1,5s/:/#/g' file1 #将第1-5行的所有:都替换为#
sed '1s/:/#/g' file1 #将第1行的所有:都替换为#
sed '1s/:/#/g;5s/:/#/g' file1 #将第1和5行的所有:都替换为#
sed '/lp/,/shutdown/s/:/#/g' file1 #将含lp与shutdown行的所有:都替换为#
sed 's/\//##/g' file1 #将file1所有行的所有/替换为##
sed 's@/@##@g' file1 #将file1所有行的所有/替换为##
字符操作:
字符匹配替换:
练习及脚本 Apache_port.sh http的端口就改为此数字:
#!/bin/bash
[ -e $1 ]&&{
echo "Please input port number following script! "
exit
}
lsof -i:$1 &>/dev/null &&{
echo "$1 is used! "
}||{
sed "/^Listen/cListen $1" -i /etc/httpd/conf/httpd.conf
systemctl restart httpd
}
3. awk
awk命令可以将文本进行分割,并且进行指定操作
用法:
[root@rhserver Desktop]# awk -F 分隔符 [script] [FILE]
[root@rhserver Desktop]# awk -F 分隔符 BEGIN{}{}END{} FILE
#筛选条件
/条件1|条件2/ #条件1或者条件2
/条件1/||/条件2/ #条件1或者条件2
/条件1/&&/条件2|条件3/ #条件1并且(条件2或条件3)
$0 #所有的列
$1 #第一列
$2 #第二列
$3 #第三列
awk -F : '$6!~/home/&&/bash$/{print}' /etc/passwd
#/etc/passwd文件的第六列没有home关键字并且以bash结尾的行
统计在系统中能su切换的并且用户加目录不在/home下的用户数量:
#!/bin/bash
awk -F : 'BEGIN{n=0}$6!~/^\/home/&&/\/sh$|\/bash/{n++}END{print n}' /etc/passwd