首页 > 其他分享 >正则表达式和sed

正则表达式和sed

时间:2023-09-07 10:38:56浏览次数:30  
标签:grep 正则表达式 etc sed passwd file root

case var in

    模式1|模式1-1)

       command。。。

        ;;

    *)

      command...

       ;;

esac


function_name(){

command

...

}


function fun_name(){

command

...

}


正则表达式:

前导字符(位于元字符前的字符);元字符就是在正则里具有特殊含义的特殊字符

.:匹配换行符以外其他任意单个字符

*:前导字符出现0次或连续出现多次ab* ab abb abbb

.*:任意长度的字符

^:行首

$:行尾

^$:空行

[]:匹配在指定字符组内的任意字符

[^]:匹配不在指定字符组内的任意字符

^[]:匹配以指定字符组内的任意字符开头

^[^]:匹配不以指定字符内的任意字符开头

\<:取单词的头

\>:取单词的尾

\<\>:精确匹配某个单词

\{n\} {n}:匹配前面字符连续出现n次

\{n,\} {n,}:匹配前面字符至少出现n次

\{n,m\} {n,m}:匹配前面字符出现n到m之前

\(\):保留被匹配到的字符



+:前导字符连续出现一次或多次

?:前导字符连续0次或一次

\d: [0-9]  匹配数字0-9

\w: [a-zA-Z0-9_] 匹配数字,字母,下划线

\s:匹配换行,制表格,空格等特殊字符


实例:

192.168.1.254 ——>192.168.0.254

\(192\.168\.\)1.254


sed -n 's/\(192\.168\.\)1.254/\10\.254/p'

sed -n 's/\(192\.168\)\.1.254/\1\.0\.254/p'


\(192\.168\.\)1\(\.254\)

sed -n 's/\(192\.168\.\)1\(\.254\)/\10\2/p'

sed -n 's#\(192\.168\.\)1\(\.254\)#\10\2#p'


helloworld myself ——>hellolilei yourself


\(hello\)world my\(self\)


sed -n 's/\(hello\)world my\(self\)/\1lilei your\2/p'


扩展正则:

grep -E 或者egrep

# grep -E 'root|ftp|halt' /etc/passwd

# egrep 'root|ftp|halt' /etc/passwd

# grep -E 'g+' 1.txt

# grep -E 'g?' 1.txt


# grep -P '\d' 1.txt

# grep -P '\w' 1.txt

# grep -P '\s' 1.txt


通配符:* ?

正则:* ?



第二类正则:


大写 [[:upper:]] [A-Z]

小写 [[:lower:]] [a-z]

字母 [[:alpha:]] [a-Z] [a-zA-Z]

制表符 [[:blank:]]

空格 [[:space:]]

纯数字 [[:digit:]] [0-9]

标点符号 [[:punct:]]

字母数字 [[:alnum:]] [a-Z0-9]




练习:

1、查找不以大写字母开头的行(三种写法)

  # grep ^[^A-Z] file.txt

2、查找有数字的行

  # grep -E '\d' file.txt

3、查找一个数字和一个字母连起来的行

  # grep [0-9][a-Z] file.txt

4、查找不以r开头的行

  # grep ^[^r] file.txt

5、查找以数字开头的行

  # grep ^[0-9] file.txt

6、查找以大写字母开头的行

  # grep ^[A-Z] file.txt

7、查找以小写字母开头的行

  # grep ^[a-z] file.txt

8、查找以.点结束的

  # grep [\.]$ file.txt

9、去掉空行

  # grep . file.txt

10、查找完全匹配abc的行

  # grep -E abc? file.txt


11、查找A后有3个数字的行

12、统计root在/etc/passwd里出现了几次

# grep -o root /etc/passwd|wc -l

13、用正则表达式截取自己的ip地址、广播地址、子网掩码

ifconfig eth0|grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"

ifconfig eth0|grep -o "\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}"


14、找出文件中的ip地址并打印换成192.168.1.254

sed -n 's/\(192\.168\)\.0\.\(254\)/\1\.1\.\2/p'

15、找出文件中的ip地址打印出来

# grep "\([0-9]\{1,3\}\.\)\{3\}[0-9]\{3\}" 2.txt

# grep -P "\d+\.\d+\.\d+\.\d+" 2.txt


file.txt

UIYkdjfkdjf983748kfddkfjd

akdfj9874f dkjf?()*YI^&.,.l

rlkfl9089uJKGHIOUN*^%&$%^)()


634dkfjf(*&(*Jklnmfkdnlk;

kfdjA7876 098&**KJHNJK.

A789lkdfhkJKHJKLN.


192.168.0.254

djabc(*kldjfkdKJHJKLNL.

kjsdfhJKHGKJLHNKLabc308949&*^*

7867LKJHKLJ4552*(&)(



vi vim gedit emacs nano  特点:交互式


sed:流编辑器 非交互式  行处理  临时空间 默认不会直接修改源文件


命令模式: sed 选项 '命令清单<函数|定址>' filename

脚本模式: sed -f file.sed filename

        #!/bin/sed -f   建议

         command...



命令模式:

选项:

-e:进行多项编辑

-n:取消默认输出

-f:指定脚本文件

-r:扩展正则

-i:重定向输出(直接修改源文件)


命令清单:

a\(a):在当前行行后面添加内容

i\(i):在当前行的前面添加内容

c\ :用该符号后面的内容替换到匹配到的内容


d:删除行

p:打印行

r:从文件中读取行

w:保存到文件

s:搜索替换

!:对所选的行以外的行应用相应的命令

g:全局

y:将字符替换成另一个字符

&:保留查找的字符串

=:打印号


定址:

x 指定x行  sed -n 'xp' file

x,y 指定x行到y行   sed -n '1,5p' file

x,y! 匹配x行到y行以外的行 sed -n '1,38!p' /etc/passwd

/key/  匹配key关键字  sed -n '/root/p' file

/key/,x 匹配key关键字后的x行(包含关键字所在行)  sed -n '/^root/,5p' file

x,/key  从x行开始匹配到key关键字  sed -n '5,/root/p' file

/key1/,/key2/  从匹配到key1开始,匹配到key2结束 sed -n '/^root/,/^ftp/p' file


实例:

p命令 打印

sed '1p' file

sed '2,5p' file

sed -n '/root/p' file

默认情况,打印文件所有行和匹配到的行;-n只打印匹配到的行,-n和p一起使用


d删除

# head -5 /etc/passwd|sed '/root/d'

# head -5 /etc/passwd|sed '1,3d'

# head -5 /etc/passwd|sed '1,3!d'


s搜索替换

# sed -n 's/root/hello/gp' /etc/passwd

# sed -n 's/bash$/uplooking/gp' /etc/passwd

# sed -n 's/\/bin\/bash/\/sbin\/nologin/gp' /etc/passwd

自定义分割符:

# sed -n 's#/bin/bash#/sbin/nologin#gp' /etc/passwd


r读取文件内容到匹配行

# sed '/^root/r 1.txt' /etc/passwd

# sed '/root/r 1.txt' /etc/passwd  在匹配到root的所有行下面追加1.txt文件内容


w另存为

# sed  '/root/w 3.txt' /etc/passwd  屏幕打印所有,并将匹配到的内容保存到3.txt文件中

# sed -n '/root/w 3.txtp' /etc/passwd  屏幕上不输出,直接保存到文件


a\ (a):在匹配行的后面插入内容

# sed '/root/a hello' /etc/passwd

# sed '/^root/a\ hello world' /etc/passwd|head

# sed '/^root/a\

hello\

world\

888' /etc/passwd


sed '1,5a hello' file  1-5行的每一行下面插入内容

sed 'a hello' file  每一行后面插入内容

sed '$a hello' file  最后一行的后面插入内容


i\ (i):在匹配行的前面插入内容

# sed '/^root/i 888' /etc/passwd|head

# sed '/^root/i\

> hello\

> world\

> 999' /etc/passwd


sed '7a hello' file  第7行的上面插入内容

sed 'i hello' file  每一行上面插入内容

sed '$i hello' file  最后一行的前面插入内容


c\ (c) 替换已有的文本

# sed '/^root/c 88888' /etc/passwd|head

# sed '/root/c\

> hhahahahahahh\

> 9999999' /etc/passwd|head -20


sed '7c hello' file

sed '1,5c hello' file  

sed '$c hello' file


y命令 类系tr 替换 对正则表达式里的元字符不起作用


# sed '39,43y/stu/STU/' /etc/passwd|tail

# sed '39,43y/stu\:x/STU@%/' /etc/passwd|tail


-e多项编辑

# sed -e 's/root/hello/g' -e '/^stu/d' /etc/passwd

# sed -ne 's#/bin/bash#uplooking#gp' -e '/^root/c 9999' /etc/passwd


& 保留所匹配到的内容

# sed -n 's/^stu/#&/p' /etc/passwd

# sed -n 's/^#//p' passwd

# sed -n 's/^[0-9]/#&/p' 1.txt

# sed -rn 's/^root|^ftp/#&/p'

# sed -nr 's/^root|^ftp/#&/p' /etc/passwd


= 打印行号

# sed -e '/root/=' -ne '/root/p' /etc/passwd

# sed -ne '/root/p' -e '/root/=' /etc/passwd


-i 直接修改源文件

# sed -i 's/^stu/#&/p' passwd  注意:-i参数后面的p重复在源文件中出现,慎用

# sed -i 's/^#//' passwd


课堂练习:

cp /etc/passwd /tmp

1、打印匹配将任一数字替换成空或者制表符

# sed -n 's/[0-9]//gp' passwd

# sed -n 's/[0-9]/\t/gp' passwd

2、去掉文件1-5行的数字、冒号、斜杠

# sed -n '1,5s/[0-9:/]//gp' passwd

# sed -nr '1,5s#[0-9]|:|/##gp' passwd

# sed -nr '1,5s/[0-9]|:|\///gp' passwd

3、匹配root关键字的行替换成hello uplooking,并保存到test.txt文件中

# sed 's/root/hello uplooking/gw  test.txt' passwd

4、删除vsftpd.conf、smb.conf、main.cnf文件中不生效的行(不要直接修改原文件)

# sed -e '/^#/d;/^$/d' vsftpd.conf

# sed -e '/^#/d' -e '/^$/d' vsftpd.conf

# sed -r '/^#|^$/d' vsftpd.conf


# sed -r '/^#|^;|^$|^\t$/d' smb.conf

# sed -e '/^#/d;/^;/d;/^$/d;/^\t$/d' smb.conf


# sed -r '/^#|^\t$|^$/d' main.cf

5、使用sed截取自己的ip地址

# ifconfig eth0|sed -n '2p'|sed -n 's/^.*inet addr://gp'|sed -n 's/Bcast.*//gp

6、使用sed截取除自己的ip地址、广播地址、子网掩码

# ifconfig eth0|sed -n '2p'|sed -n 's/.*inet addr:\(.*\) Bcast:\(.*\) Mask:\(.*\)/\1\n\2\n\3/p'

7、注释掉文件中5-10行

# sed -n '5,10s/^/#/gp' passwd





课后练习:

1、写一个初始化系统的脚本

1)自动修改主机名(如:ip是192.168.1.2,则主机名改为server2.uplook.com)

2)自动配置可用的yum源

3)自动关闭防火墙和selinux

2、写一个自动搭建ftp服务的脚本,要求如下:

1)不支持本地用户登录

2)匿名用户可以上传、新建、删除

3)匿名用户限速500kbps


思路:

1、过滤出自己的ip地址——>hostname——>/etc/sysconfig/network(sed -i)

2、判断本机网络是否和内网yum仓库服务器通——>配置yum源——>安装相应的软件

3、关闭防火墙和selinux——>/etc/selinux/config(sed -i)


4、修改配置文件/etc/vsftpd/vsftpd.conf(sed -i)

5、启动服务测试验证


vim vsftpd.sh

#!/bin/bash

#初始化操作系统(修改主机名、关闭防火墙和selinux、配置yum源)

ipaddr=`ifconfig eth0|sed -n '2p'|sed -e 's/.*inet addr:\(.*\) Bcast.*/\1/g'`

iptail=`echo $ipaddr|cut -d"." -f4`

ipremote=192.168.1.2


#修改主机名

hostname server$iptail.uplook.com

sed -i "/HOSTNAME/c\HOSTNAME=server$iptail.uplook.com" /etc/sysconfig/network

echo $ipaddr server$iptail.uplook.com >> /etc/hosts


#关闭防火墙和selinux

service iptables stop

chkconfig iptables off

setenforce 0 &>/dev/null

sed -i '/^SELINUX=/c\SELINUX=disabled' /etc/selinux/config


#配置yum源(内网源)

ping -c 1 $ipremote >/dev/null 2>&1

if [ $? -eq 0 ];then

  echo "网络ok"

else

  echo "网络有问题,请检查你的网络"

  exit 1

fi


rm -f /etc/yum.repos.d/*

cat > /etc/yum.repos.d/server.repo <<end

[server]

name=xxx

baseurl=ftp://$ipremote/rhel6_dvd

enabled=1

gpgcheck=0

end


#安装相应的软件

read -p "请输入你所需要安装的软件(多个软件空格隔开):" soft

yum -y install $soft &>/dev/null


#根据需求搭建ftp服务

conf=/etc/vsftpd/vsftpd.conf

cp $conf $conf.bak

sed -ri '/^#|^$/d' $conf

sed -i '/local_enable/c\local_enable=NO' $conf

sed -i '$a anon_mkdir_write_enable=YES' $conf

sed -i '$a anon_other_write_enable=YES' $conf

sed -i '$a anon_upload_enable=YES' $conf

sed -i '$a anon_max_rate=512000' $conf


#启动服务

service vsftpd restart &>/dev/null && echo "服务已经运行"


#测试验证

dir=/var/ftp

chmod o+w $dir/pub

cd /tmp

cp /etc/hosts $dir/pub


lftp $ipaddr <<end

cd pub

get hosts

put /etc/group

mkdir dir1

mkdir dir2

rmdir dir2

exit

end


if [ -d $dir/pub/dir1 ];then

  echo "目录创建成功"

  if [ ! -d $dir/pub/dir2 ];then

    echo "目录删除成功"

  fi

fi


[ -f $dir/pub/group ] && echo "文件上传成功"




标签:grep,正则表达式,etc,sed,passwd,file,root
From: https://blog.51cto.com/u_12058595/7394521

相关文章

  • 正则表达式编译取值法
       还是使用《正则表达式直接取值法》中的例子,这里介绍一下用编译取值法编辑正则表达式取得我们想要的元素。text="姓名:海风,性别:男,年龄:52,账号:12345,密码:6789,作品:<<'双随机'管理系统>>电\\\话:133****5117(常用)"   采用编译取值法匹配全部字符,包......
  • 正则表达式
    正则表达式(RegularExpression)是一种文本模式,包括普通字符(例如,a到z之间的字母)和特殊字符(称为"元字符"),可以用来描述和匹配字符串的特定模式。正则表达式是一种用于模式匹配和搜索文本的工具。正则表达式提供了一种灵活且强大的方式来查找、替换、验证和提取文本数据。正则表达......
  • Android官方资料--Block-Based OTAs
    Block-BasedOTAsINTHISDOCUMENTRecommendationsFilevs.BlockOTAsUpdatingunmodifiedsystemsUpdatingmodifiedsystemsYoucanenableblock-basedover-the-air(OTA)updatesfornewdevicesrunningAndroid5.0.OTAisthemechanismbywhichOEMsremote......
  • 论文精读:带有源标签自适应的半监督域适应(Semi-Supervised Domain Adaptation with Sou
    Semi-SupervisedDomainAdaptationwithSourceLabelAdaptation具有源标签适应的半监督域适应原文链接Abstract文章指出当前的半监督域适应(Semi-SupervisedDomainAdaptation,SSDA)方法通常是通过特征空间映射和伪标签分配将目标数据与标记的源数据对齐,然而,这种面向源数......
  • A Challenge Dataset and Effective Models for Aspect-Based Sentiment Analysis
    摘要基于方面的情感分析(ABSA)由于其广泛的应用,近年来受到了越来越多的关注。在现有的ABSA数据集中,大多数句子只包含一个或多个具有相同情感极性的方面,这使得ABSA任务退化为句子级情感分析。在本文中,我们提出了一个新的大规模多方面多情感(MAMS)数据集,其中每个句子至少包含两个具有不......
  • ipv4+ipv6+端口号正则表达式,最极限的各种搭配组合
    Ipv4^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$Ipv6^([\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^::([\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25......
  • Java Socket IO流关闭问题: Exception in thread "main" java.net.SocketException: S
    先说结论问题:明明执行的语句在socket.close前,却出现Exceptioninthread"main"java.net.SocketException:Socketisclosed报错结论:在Java中关闭一个包装流会导致它的底层流也被关闭所以一般使用socket.shutdownOutput()或socket.shutdownInput()关闭对应的流问题复现......
  • 正则表达式直接取值法
        请使用正则表达式方法提取以下文字中的姓名、性别、年龄、账号、密码、作品和电话号码。要求只提取项目内容,电话号码使用状态不提取。text="姓名:海风,性别:男,年龄:52,账号:12345,密码:6789,作品:<<'双随机'管理系统>>电\\\话:133****5117(常用)" 采用直接......
  • 正则表达式,几种常见的量词
    当处理正则表达式时,通常会遇到以下几种常见的量词:*:匹配前面的表达式零次或多次。例如,a*b可以匹配"b","ab","aab","aaab"等。+:匹配前面的表达式一次或多次。例如,a+b可以匹配"ab","aab","aaab"等,但不能匹配"b"。?:匹配前面的表达式零次或一次。例如,a?b可以匹......
  • Caused by: java.sql.SQLSyntaxErrorException: ORA-00923: 未找到要求的 FROM 关键字
    最终是,查询条件,入参为null,所导致。JDBCgetParameterTypecallfailed-usingfallbackmethodinsteadRA-00923:FROMkeywordnotfoundwhereexpected 进一步,这个错误,在job执行的时候,会导致,oracle游标不够ORA-01000maximumopencursorsexceeded   参考: ......