Shell学习(七)

grep sed awk 练习

系列学完了,这是第二期。(其实应该这个先学的) bash 基础
接下来是有名的第三方工具 (正则表达式 awk sed grep等等)

grep

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 找出有关 root 的行
grep "root" /etc/passwd
# 找出有关 root 开头的行
grep "^root" /etc/passwd
# 匹配咦 root 开头或者与 feng 开头的行
grep -E "^(root|feng)" /etc/passwd
# 过滤以 bin 开头的行,前面显示行号
grep -n "^bin" /etc/passwd
# 过滤掉除了 nologin 结束的行
grep -v "nologin$" /etc/passwd
# 统计 bash 出现次数
grep -c "bash" /etc/passwd
# 过滤 bash 的行,之匹配两次
grep -m 2 "bash" /etc/passwd
# 匹配多个文件,只列出存在信息文件的名字
grep "www" /etc/passwd /etc/apache2/apache2.conf
grep -l "www" /etc/passwd /etc/apache2/apache2.conf
# 找出 /etc/passwd 中的两位数或者三位数
# \< 左闭合 \> 右闭合 不然会匹配这种:"123"4 或者 1"234"
grep -E "\<[0-9]{2,3}\>" /etc/passwd
# 找出文件中,空行开头,但后面有非空格的行
grep -E "^ .{1,}" 1.txt
grep "^[[:space:]].*" 1.txt
grep -E "^[[:space:]]+[^[:space:]]" 1.txt
# 找出文件中,以大小写aA开头的行
grep -i "^a" 1.txt
grep -E "^(a|A)" 1.txt
grep "^[aA]" 1.txt
# 找出脚本中的函数名
grep "[a-zA-Z]*[[:space:]]*()" /etc/init.d/mariadb
grep -E "[a-zA-Z]*[[:space:]]*\(\)" /etc/init.d/mariadb
# 找出用户名和解释器相同的行
grep -E "^([^:]+\>).*\1$" /etc/passwd --color=auto



sed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 替换和全局替换
sed 's/root/feng/p' /etc/passwd -n
sed 's/root/feng/gp' /etc/passwd -n
# 替换前 10 行 s 开头的用户改为 c 且仅仅打印替换后的结果
sed -n '1,10s/^s/c/gp' /etc/passwd
# 替换前 10 行 s 开头的用户改为 c; m 改为 p 且仅仅打印替换后的结果
sed -n -e '1,10s/^s/c/gp' -n -e '1,10s/^m/p/gp' /etc/passwd
# 删除4行后面所有
sed -n '1,4p' /etc/passwd
sed '5,$d' /etc/passwd
# 删除 bin 开始,到 dradis 之间的行
sed '/^bin/,/^dradis/d' /etc/passwd
# 将文件中的空格开头的行,加上注释
cat 1.txt
sed 's/^[[:space:]]/# /g' 1.txt
# 删除文件中的空行和注释行
sed -e '/^$/d' -e '/^[[:space:]]/d' 1.txt
sed -e '/^$/d;/^[[:space:]]/d' 1.txt
# 给文件前 3 行加上 @ 符号
sed '1,3s/^/@/g' 1.txt
sed -r '1,3s/(^.)/@\1/' 1.txt


awk

文章作者: Shengyaqingfeng
文章链接: https://creazyboyone.github.io/shell7/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Shengyaqingfeng's Blog