linux中shell的awk和sed简介

1.sed命令

sed:stream editor :一次处理一行内容,处理时,把当前的行存储在临时缓冲区,处理完后,输送到屏幕

sed [参数]  '命令' file
      p	                    ##显示
      d	                    ##删除
      a	                    ##添加
      c	                    ##替换
      i	                    ##插入

1)p:

sed -n '/\:/p' /etc/fstab                   ##显示有:的行
sed -n '/^#/p' /etc/fstab                   ##显示#开头的行
sed -n '/^#/!p' /etc/fstab                  ##显示不以#开头的行
sed -n '2,6p' /etc/fstab                    ##显示第2-6行
sed -n '2,6!p' /etc/fstab                   ##显示2到6行以外的行

2)d:

sed '/^UUID/d' /etc/fstab                 ##删除UUID开头的
sed '/^#/d' /etc/fstab                    ##删除空行
sed '/^$/d' /etc/fstab                    ##删除以$开头的
sed '1,4d' /etc/fstab                     ##删除1到4行

3)a:

sed '/hello/aworld' westos                        ##在westos里的hello后添加world
sed 's/hello/hello world/g' westos                ##实际效果是在hello后添加了world
sed 's/hello/hello\nworld/g' westos               ##实际效果是hello后面换行后添加了world

4)c:替换

sed '/hello/chello world' westos            ##将hello替换成hello world

5)i:

sed '/hello/iworld\nwestos' westos                 ##hello之前插入world 换行 westos

6)-i:改变原文件内容

sed -i 's/westos/redhat/' passwd             ##每一行的第一个替换
sed -i 's/westos/redhat/g' passwd            ##全局替换

2.awk报告生成器 

 this   |  is  |  a  |  file                                                  ##如下,awk把变量分为了四列
 $1       $2   $3  $4

awk '{print $0}' test	                ##$0表示输出一整行

awk '{print $1}' test	                ##输出第一个变量

awk '{print $4}' test	                ##输出第四个变量

awk '{print $1,$2}' test	        ##显示两个字段

awk -F ":" '{print $1,$3}' /etc/passwd	##指定:为分隔符,并输出1,3列

1)awk的常用变量

awk '{print FILENAME,NR}' /etc/passwd	##输出文件名,和当前操作的行号

awk -F: '{print NR,NF}' /etc/passwd	##输出每次处理的行号,以及当前以":"为分隔符的字段个数

总结:awk '{print "第NR行","有NF列"}' /etc/passwd

BEGIN{}:读入第一行文本之前执行的语句,一般用来初始化操作
{}:逐行处理
END{}:处理完最后以行文本后执行,一般用来处理输出结果

awk 'BEGIN { a=34;print a+10 }'

awk -F: 'BEGIN{print "REDHAT"} {print NR;print } END {print "WESTOS"}' passwd         ##文件开头加REDHAT,末尾加WESTOS,打印行号和内容

awk -F: '/bash$/{print}' /etc/passwd    ##输出以bash结尾的

awk -F: 'NR==3 {print}' /etc/passwd

awk -F: 'NR % 2 == 0 {print}' /etc/passwd    ##偶数行

awk -F: 'NR >=3 && NR <=5 {print }' /etc/passwd

awk 'BEGIN{i=0}{i+=NF}END{print i}' linux.txt    ##统计文本总字段个数

 2)if双分支

awk -F: 'BEGIN{i=0;j=0}{if($3<=500){i++}else{j++}}END{print i,j}' /etc/passwd    ##统计uid小于等于500和大于500的用户个数 

3)for循环

awk 'BEGIN{for(i=1;i<=5;i++){print i}}'                ##输出1.2.3.4.5

3.一些脚本来加深印象

1)自动安装http并修改端口

#!/bin/bash
yum install -y httpd &> /dev/null
sed -i "/^Listen/cListen $1" /etc/httpd/conf/httpd.conf
echo -e "Port has changed!"
echo "Now ,Port is $1!"
systemctl restart httpd

2)列出uid小于2的用户信息

#!/bin/bash

#练习:列出uid小于2的用户信息

awk -F: '$3 >= 0 && $3 < 2 {print $1,$3}' /etc/passwd

猜你喜欢

转载自blog.csdn.net/weixin_40543283/article/details/85274778
今日推荐