shell文本处理grep、egrep和cut命令(文本处理一)

编程入门 行业动态 更新时间:2024-10-28 16:20:17

shell<a href=https://www.elefans.com/category/jswz/34/1771357.html style=文本处理grep、egrep和cut命令(文本处理一)"/>

shell文本处理grep、egrep和cut命令(文本处理一)

 

  

一、grep,egrep

1. Grep定义

    grep 命令是一种强大的文本搜索工具,根据用户指定的“模式”对目标文本进行匹配检- 查,打印匹配到的行
    由正则表达式或者字符及基本文本字符所编写的过滤条件
    Global search regular expression and print out the line
    全面搜索研究正则表达式并显示出来

2、Grep用法
grep [匹配条件] [处理文件]

3、Grep参数
-i 忽略字母大小写
-v 条件取反
-c 统计匹配行数
-q 静默,无任何输出
-n 显示匹配结果所在的行号

    -q:

 [root@server mnt]# grep '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
172.25.254.250 content.example
YES
[root@server mnt]# grep -q '172.25.254.250' /etc/hosts && echo 'YES' || echo 'NO'
YES

   

    -c

[root@server mnt]# egrep -c '/sbin/nologin' /etc/passwd
35

 

    基本元字符:^ $

[root@server mnt]# egrep '^root' /etc/passwd  ##匹配以字符串 root 开头
root:x:0:0:root:/root:/bin/bash

[root@server mnt]# cat wsp
root sbin
root sbin root
root sbin sbin
[root@server mnt]# egrep 'sbin$' wsp  ##匹配以字符串 sbin 结尾
root sbin
root sbin sbin

 

    基本元字符:.    过滤非空行

[root@server mnt]# egrep '.' wsp
root sbin
root sbin root
root sbin sbin
root
awd
awd
awd

  

过滤空行

[root@server mnt]# egrep -v '.' wsp        ##过滤空行
[root@server mnt]# egrep  '^$' wsp        ##过滤空行

   

    基本元字符: + ? *

[root@server ~]# egrep 'f+' 1.sh     ##输出包括f,ff,fff....,即至少出现一次
colorful,color
colorfulful?
stuf
stuff
stufff
stuffff
stufawd
we adw dfg awda
wea web wef

[root@server ~]# egrep 'color(ful)?' 1.sh     ##末尾的ful最多出现一次,也可以没有
color color color
colorful,color
color color.
colorfulful?

*为匹配所有

   

    元字符:{}

[root@server ~]# egrep '(we){3}' 1.sh   ##精确匹配三个we所在行
rere wewewe
westos wewewewe Shell
[root@server ~]#
[root@server ~]#
[root@server ~]# egrep '(we){2,4}' 1.sh  ##匹配2-4个we所在行
xcvb wewe asdawd
rere wewewe
westos wewewewe Shell
[root@server ~]#
[root@server ~]# egrep '(we){3,}' 1.sh   ##匹配三个及以上we所在行
rere wewewe
westos wewewewe Shell
[root@server ~]# egrep '(we)[ab]' 1.sh   ##匹配we后为a或b所在行
weawe IPADDR
wea web wef
[root@server ~]# egrep '[A-Z]' 1.sh     ##匹配含有大写字母A-Z所在行
weawe IPADDR
westos wewewewe Shell

 

二、cut命令

cut -d            ##指定分隔符
cut -d : -f 1-3 /etc/passwd        ##指定分隔符为:,显示第1到3列
cut -c 1,4 /etc/passwd            ##显示第一和第四个字符

 

三、练习

    获取主机IP

 [root@server ~]# ifconfig eth0 | grep "inet " | awk '{print $2}'
172.25.254.100

[root@server ~]# ifconfig eth0 | grep "inet " | cut -d " " -f 10
172.25.254.100

   

    检测网络

[root@server ~]# vim ping.sh
ping -c1 -w1 172.25.254.$1 &> /dev/null && echo 172.25.254.$1 is up || echo 172.25.254.$1 is down
[root@server ~]# sh ping.sh 19
172.25.254.19 is up

  

 
 

更多推荐

shell文本处理grep、egrep和cut命令(文本处理一)

本文发布于:2024-02-27 12:39:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1706542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   命令   shell   grep   cut

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!