目录
- Shell之三剑客
- 参考
- Grep
- Sed
- Awk
Shell之三剑客
Written by Zak Zhu
学习python风格, 优雅规范书写shell代码
参考
- 马哥linux视频
- RHCE培训
Grep
Global search Regular Expression and Print out the line
grep [OPTIONS] "PATTERN" [FILE...]
Options:
-E, --extended-regexp # equal to "egrep"
-i, --ignore-case
-n, --line-number
-v, --invert-match
-o, --only-matching # show only the part of a line matching PATTERN
-r "PATTERN" DIR # 根据文件内容, 查找文件
-A NUM, --after-context=NUM
-B NUM, --before-context=NUM
-C NUM, --context=NUM
-w, --word-regexp
--color
练习:
显示/proc/meminfo文件中的以大小写s的开头的行
grep -E -i "^s" /proc/meminfo --color
取出默认shell为bash的用户
cat /etc/passwd | grep "/bin/bash" | awk -F":" '{print $1}'
找出netstat -tan命令执行的结果中以“LISTEN”或“ESTABLISHEN”结尾的行
netstat -tan | grep -E "LISTEN|ESTABLISHED" --color
显示/etc/ssh/sshd_config文件中非注释和非空白行的内容
grep -E -v "^#|^$" /etc/ssh/sshd_config
Sed
- Stream Editor for filtering and transforming text
- It's a line editor as well
- It's not modify the content of file by default, just print on the screen
- Support RE
sed [OPTIONS] "Startline,Endline EditCommand" FILE...
sed [OPTIONS] "/Pattern1/,/Pattern2/EditCommand" FILE...
sed [OPTIONS] "[Startline,Endline]s/old_pattern/new_word/[gi]" FILE...
# g global line; i ignore-case
sed [OPTIONS] "[/Pattern1/,/Pattern2/]s/old_pattern/new_word/[gi]" FILE...
Options:
-n, --silent
-i, # edit files in place
-E -r, --regexp-extended
EditCommands:
p # print (always use with the "-n" option)
d # delete
i \TEXT # insert text
a \TEXT # append text
r FILENAME # append text Read from filename
练习:
在sed_test文件的第2行和第3行中间插入一行"hello world!"
sed "3,3 i \hello world!" sed_test
在sed_test文件的含有"lover"行后追加一行"zac"
sed "/lover/a \zac" sed_test
把sed_test文件中的"like"和"liker"全部替换成"love"和"lover"
sed "s/like/love/g" sed_test
替换/etc/inittab文件中”id:3:initdefault:"一行中的数字为5
sed -i "s/:3:/:5:/" /etc/inittab
删除/etc/init.d/funcions文件中的空白行
sed "/^$/d" /etc/init.d/functions
删除/etc/inittab文件中位于行首的#
sed "s/^#//" /etc/inittab
删除/boot/grub/grub.conf文件中行首的空白字符
sed "s/^[[:space:]]+//" /boot/grub/grub.conf
Awk
报告生成工具
把文件中读取到的每一行的每个字段分别进行格式化, 而后进行显示
# 不加-F选项时, 分割符默认为空白
$NF # the built-in var "NF" is set to the Number of Fields
awk -F'SEP' '/PATTERN/{print $X}' FILE...
awk -F'SEP' '!/PATTERN/{print $X}' FILE... # !意思是取模式的非集
awk -F'SEP' 'EXPRESSION{print $X}' FILE...
EXPRESSION:
$XK
$X>=K
$X==K
$X~"PATTERN" # 取匹配模式的行
练习:
显示GID小于等于500的组
awk -F':' '$3<=500{print $1}' /etc/group
显示默认shell为nologin的用户
awk -F':' '$NF~"nologin"{print $1}' /etc/passwd
显示/usr/lib/sysctl.d/00-system.conf文件中定义的内核参数名称
awk -F' = ' '!/^#|^$/{print $1}' /usr/lib/sysctl.d/00-system.conf
通过ifconfig命令显示eth0网卡的ip地址
ifconfig eth0 | awk '/inet/{print $2}'
Oh Yeah!