Shell脚本编程——查找和过滤的常用命令(转)

  记录一下Shell脚本编程中常用的Search&Filter命令。 

1.         grep&awk/cut

 grep

grep -rsw “key” <dir>   #查找文件里的内容,(r递归,s忽略错误,w全字匹配)

grep -v key                  #不显示key所在行

pgrep 

pgrep process               #显示所有进程process的pid

fgrep  

egrep  

 

    使用示例: 

Ø        Case1:查看相关进程的PID

用grep过滤出相关进程,再用awk打印第n列。

root@~>ps -ef | grep -i telnet                   

root     1784  9927  0 16:51 pts/0    00:00:00 grep -i telnet

root     9924  3021  0 15:33 ?        00:00:00 in.telnetd: 192.168.122.85

root     15187  3021  0 14:08 ?        00:00:00 in.telnetd: 192.168.122.179

root    15341  3021  0 14:09 ?        00:00:00 in.telnetd: 192.168.122.179

root    23397  3021  0 14:33 ?        00:00:00 in.telnetd: 192.168.122.179

root@~>ps -ef | grep -i telnet | awk '{print $2}'

1791

9924

15187

15341

23397

比较简单的方法是这样:

root@~>pgrep telnet

1791

9924

15187

15341

23397

 

Ø        Case2:查看所有用户,即第1列(多行)

awk -F: '{ print $1 }' /etc/passwd

-F接隔离符,-F “:”也行

 

Ø        Case3:查找第5个,cut跟awk一样的效果

root@~> ls /var/remote/ | sort | tail -1

bi0-0-9-2-11-1

root@~> ls /var/remote/ | sort | tail -1 | cut-d"-" -f5

11

 

Ø        grep的常用参数

grep用得太多了,一些常用的参数用蓝体字标示一下呵呵

 -i, --ignore-case        ignore case distinctions

 -w, --word-regexp         force PATTERN tomatch only whole words

 -s, --no-messages        suppress error messages

 -v, --invert-match        selectnon-matching lines

 -q, --quiet, --silent     suppress all normal output

 -R,-r, --recursive       equivalent to --directories=recurse 

2.         sed&tr

Search(查找和过滤)命令应用相当广泛。比如还有sed/tr。

 

sed

sed -e ‘1,10d’ -e ’s/yellow/black/g’ test.txt

对文档text.txt执行多个命令,删除1-10行,替换所有字符串yellow为black。

-e 表示命令列,-f 表示脚本文件,比如-f mysed.script,mysed.script为

1,10d

s/yellow/black/g

另t.*t表示首尾都是t的行

 

#显示指定两行中间的trap信息

sed -n "46528,46575p"  /var/log/dbtrap.log 

3.         other search

 find

find <dir> -name key        查找文件或文件夹

find <dir> -name “*key*”    扩大范围

  可用--maxdepth n指定深度

locate   ?

whereis <file>          //查询文件的位置

 

which <cmd>           //查询命令的位置

 

whow             //查询所有登录者

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值