打印第二列为oldboy的第一列内容(awk,grep,sed用法)

 

[root@goldtest ~]# cat ip.log 
10.0.0.1 oldboy
10.0.0.2 oldgirl
10.0.0.4 tingting
10.0.0.4 oldboy
oldboy 10.10.10.5 

 

1)awk方法

[root@goldtest ~]# awk '/oldboy/{print $1}' ip.log 
10.0.0.1
10.0.0.4
oldboy
[root@goldtest ~]# awk '$2~/oldboy/{print $1}' ip.log 
10.0.0.1
10.0.0.4

2)grep方法

[root@goldtest ~]# grep -P "\S+\s(?=oldboy)" ip.log
10.0.0.1 oldboy
10.0.0.4 oldboy
[root@goldtest ~]# grep -Po "\S+\s(?=oldboy)" ip.log 
10.0.0.1 
10.0.0.4 

 

[root@goldtest ~]# grep -P "[0-9. ]+(?=oldboy)" ip.log 
10.0.0.1 oldboy
10.0.0.4 oldboy
[root@goldtest ~]# grep -Po "[0-9. ]+(?=oldboy)" ip.log 
10.0.0.1 
10.0.0.4 

3、sed方法

[root@goldtest ~]# sed -nr '/oldboy/s#(^[^ ]+).*$#\1#gp' ip.log 
10.0.0.1
10.0.0.4
oldboy
[root@goldtest ~]# sed -nr '/oldboy$/s#(^[^ ]+).*$#\1#gp' ip.log 
10.0.0.1
10.0.0.4

4、while方法

[root@goldtest ~]# cat while.sh 
while read line
do
name=`echo $line|awk '{print $2}'`
if [ "$name" = "oldboy" ]
  then
    echo $line|awk '{print $1}'
fi
done<~/ip.log

 

posted @ 2017-08-17 17:39  martin1317  阅读(1301)  评论(0编辑  收藏  举报