Shell脚本正则表达式
正则表达式的使用方法
正则表达式的作用:过滤指定文件内容
正则表达式类型:基础正则表达式、扩展正则表达式
基础正则表达式和扩展正则表达式区别
基础正则表达式: 使用grep或者sed过滤修改配置文件
扩展正则表达式: 使用egrep和awk过滤数据
创建测试文件
vim test.txt
文本内容:
he was short and fat.
He was wearing a blue polo shirt with black pants.
The home of Football on BBC Sport online.
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
The year ahead will test our political establishment to the li
PI=3.141592653589793238462643383249901429
a wood cross!
Actions speak louder than words
192.168.100.70
#woood #
#woooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.
基础正则表达式的使用
显示行号和匹配关键字符
grep -n 'home' test.txt
显示行号过滤指定开始的字符
grep -n '^the' test.txt
匹配任意单个字符显示行号
grep -n 'wo..' test.txt
匹配方括号里边字符
grep -n 'sh[io]rt' test.txt
匹配指定字符内容
grep -o 'bet' test.txt
转义字符使用过滤IP地址
grep -n -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" test.txt
扩展正则表达式的使用
查找重复字符
egrep -n 'wo+d' test.txt
匹配任意前一个字符串
egrep -n '?will' test.txt
使用或者查找字符
egrep -n 'the|The' test.txt
查找组字符
egrep -n '(the|The|o)' test.txt
sed的使用方法
sed的作用:文本文件解释工具,支持读取、修改、显示配置文件
显示符合条件内容,显示1到5行数据
sed -n '1,5p' test.txt
显示奇数行
sed -n -e '1p;3p;5p' test.txt
删除第一行数据
sed '1d' test.txt
替换数据将tast替换为TAST
sed -i 's/tast/TAST/' test.txt
将第一到三行数据迁移到18行后边
sed -i '1,3{H;d};18G' test.txt
awk的使用方法
awk的作用:逐行读取并显示指定内容
显示文件内容
awk '{print}' test.txt
实现第一列数据
awk '{print $1}' test.txt
查看第一列和第二列数据
awk '{print $1,$2}' test.txt
第一列和第二列数据使用#号作为分隔符
awk '{print $1"#####"$2}' test.txt
查看第一行和第二行
awk 'NR==1,NR==2{print}' test.txt
显示第七列数据
awk -F : {'print $7'} /etc/passwd