grep
for i in `ls *`;do ll ${i};grep -n ^$ ${i};done //查看目录下所有文件有没有空行
grep -l "hello word" *; //打印所有文件中有hello word字符串的文件
find
find ./ -type f -name "*.sh" -o -name "*.txt" -exec grep -i "hello world" {} \+; //查找文件中包含指定字符串hello world的txt或者sh文件 ----+号表示输出文件名
find / -size -100 -print; //显示文件大小小于100 blocks 。(1 blocks = 512 字节)
find / -size +100 -print; //显示文件大小大于100 blocks
find / -name core -exec rm {} \; //查找并删除core文件
find . -exec chown $LOGNAME {} \; //修改一个目录下的所有文件的用户所属
find .-type d -exec chmod 770 {} \; //修改一个目录下的所有目录的权限
find ./ -type f -name '*.ini' |xargs grep -i 'content'; //查询一个目录下*.ini文件有没有指定的内容
find /etc -name "passwd*" -exec grep "chen" {} \; //查找etc下passwd文件有没有chen字符串
sed
sed -i '127,128s%#%%' helo.txt; //把127-128行删除#
sed -i '130,131s/^/#&/' helo.txt; //在helo.txt文件的130-131行首添加#
sed -i '/aiuap ALL=(root)NOPASSWD/'d sudoers; //删除sudoers文件包含aiuap ALL=(root)NOPASSWD的行
sed -i '51s/^/ /' helo.txt; //在51行首插入4个空格
sed -i "1d" helo.txt; //删除第1行
sed -i "1,3d" helo.txt; //删除第一行到第三行
sed -i "$d" helo.txt; //删除最后一行
sed -i '2a\this is a test line' helo.txt; // helo.txt文件第2行之后插入 this is a test line
sed -n -e '/root/=' helo.txt; //打印chenqj在helo.txt所在的行号。这里需要用等号(-n取消默认输出)
sed -n '/root/p' passwd; //打印root所在的那一行,这里需要用p正则(-n取消默认输出)
sed '1,3 w output.txt' input.txt; //将input.txt文件的1到3行吸入到output.txt
sed -r 's/^.//g' passwd 删除文件每行的第一个字符
sed -r 's/^(.)(.)/\2/g' input.txt 删除文件每行的第二个字符
sed -r 's/(.)$//g' input.txt 删除文件每行的最后一个字符
sed -r 's/(.)(.)$/\2/g' input.txt 删除文件每行的倒数第二个字符
sed -r 's/^(.)(.)/\2\1/g' passwd 交换每行的第一个字符和第二个字符
sed -r 's/[0-9]//g' passwd 删除一个文件中所有的数字
sed -r 's/^ //g' passwd 删除每行开头的所有空格
sed -r 's/[A-Z]/(&)/g' passwd 把所有大写字母用括号()括起来
awk
阮一峰awk教程
awk -F ":" '{count++;print $1} END{print "user count is ",count}' /etc/passwd //使用end模块,统计passwd人数
awk -F ":" 'BEGIN {count=0;print "[start] user count is ",count} {count=count+1;print $1} END{print "[end] user count is ",count}' /etc/passwd; //使用begin和end模块,打印姓名和总人数
ll |awk 'BEGIN {size=0;} {size=size+$5;} END{print "[end]size is ",size/1024/1024,"M"}'; //统计文件夹下文件总大小
awk '{if(NR>=20 && NR<=30) print $1}' test.txt; //查看第20到第30行的内容
awk 'END{ print NR }' filename; //统计文件中的行数
awk '{a="60074|"; b="|IVRYYPZ"; c=(substr($1,9,3)); d=(a""$1"|"c""b); print d}' //支持字符串函数
awk -F '_' '{print $1 "_" $2 "_" $3 ".unl"}'; //字符串拼接
函数:
awk -F ':' '{ print toupper($1) }' demo.txt; //函数toupper()用于将字符转为大写
tolower():字符转为小写
length():返回字符串长度
substr():返回子字符串
sqrt():平方根
rand():随机数
条件
awk -F ':' '/usr/ {print $1}' demo.txt; //print命令前面是一个正则表达式,只输出包含usr的行
awk -F ':' 'NR >3 {print $1}' demo.txt; //输出第三行以后的行
awk -F ':' '$1 == "root" || $1 == "bin" {print $1}' demo.txt; //输出第一个字段等于指定值的行
awk -F '|' 'length($2) != "11" {print $0}' 60059_20181226.UNL|head -10 //筛选指定列的长度为11的行