shell编程——sed命令基础

shell对文件的操作

初识sed命令

  • sed应用场景

    ​ 非交互式通过脚本对文件进行修改

  • sed介绍

    ​ sed是linux中提供的一个外部命令,它是一个行(流)编辑器,非交互式的对文件内容进行增、删、改、查的操作,使用者只能在命令行输入编辑命令、指定文件名,然后再屏幕上查看输出

sed语法

​ sed [options] '{command}{flags}' [filename]

​ options 命令选项

​ command sed命令

​ flags sed标志

​ filename 数据源

命令选项 说明
e 在处理输入时,将script 中指定的命令添加到已有的命令中,多条件, 一行中有多个操作
f 在处理输入时,将file中指定的命令添加到已有的命令中
n 抑制自动输出
i 非交互式的修改文件内容,修改不可逆
r 使用扩展的正则表达式
-i.bak 修改时同时创建.bak备份文件
! 取反,跟在模式条件后与shell有所区别
命令 说明
a 在匹配后面添加
i 在匹配前面添加
d 删除
s 查找替换 字符串
c 更改
y 转换 N D P
p 打印
标志 说明
数字 表示新文本替换的模式
g 全局实例
p 打印原始的内容
w filename 将替换的结果写入文件

sed使用技巧

  • 显示行号
    • sed "=" filename
  • 添加注释
    • sed -r 's/^(Listen)/s/#' filename
  • 不看注释行
    • sed -n -r '/(#|$)/!p' filename

Q&A

系统初始化脚本
1.关闭防火墙
2.关闭selinux
3.ntp时间服务器(ntp1.aliyun.com,ntp2.aliyun.com)
4.更新系统软件包

#!/bin/bash
# 1.turn off the firewalld
systemctl stop firewalld.service
systemctl disable firewalld.service

# 2.trun off the selinux
sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config

# 3.the config of chrony server
sed -i '2a\server ntp1.aliyun.com iburst\nserver ntp2.aliyun.com iburst' /etc/chrony.conf
systemctl restart chronyd
systemctl enable chronyd

# 4.update the sys app
yum update

sshd服务初始化脚本
1.修改sshd端口为12345
2.限制root用户直接登录
3.禁用公钥方式登录
4.只允许192.168.1.0/24网段的机器通过ssh协议访问服务器

[root@local_vir ~]# vim sshd_init.sh 
#!/bin/bash
# 1. 修改sshd端口为12345
sed -i '/#Port 22/a\Port 12345' /etc/ssh/sshd_config

# 2.限制root用户登录
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

# 3.禁用公钥方式登录
sed -i '/#PubkeyAuthentication yes/a\PubkeyAuthentication no' /etc/ssh/sshd_config

# 4.allow 192.168.1.0/24 
touch /etc/hosts.allow
echo "sshd:192.168.1.:allow" >> /etc/hosts.allow

image

posted @ 2022-05-09 16:43  已经周末了很忙吗  阅读(173)  评论(0)    收藏  举报