码迷,mamicode.com
首页 > 其他好文 > 详细

awk 编程

时间:2015-03-03 18:49:33      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:awk   linux   编程   nf   nr   onf   

awk

[root@localhost ~]# awk ‘{print $0}‘ /etc/passwd

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

[root@localhost ~]# awk ‘{print ""}‘ /etc/passwd


[root@localhost ~]# awk ‘{print "hihi"}‘ /etc/passwd

hihi

hihi

hihi

hihi

[root@localhost ~]# awk -F":" ‘{print $1 ":" $2}‘ /etc/passwd

root:x

bin:x

daemon:x

adm:x

awk 编程

NF:输出的字段个数

1)awk ‘{print NF}‘

2)awk ‘{print $NF}‘   读取输出行的第 个字段

3)awk ‘BEGIN{}‘

awk ‘BEGIN {FS="[:, ]"} print $0‘ /etc/passwd

awk ‘BEGIN {print toupper("hello"); print tolower("WORLD")}‘

4)awk ‘/pattern/{action}‘ file

zdd.txt

t Price/lbs

Banana 0.89

Paech 0.79

Kiwi 1.50

Pineapple 1.29

Apple 0.99

 

[root@localhost ~]# awk ‘/[1-9]\.[0-9][0-9]$/ {print $0,"*"}‘ zdd.txt

Kiwi 1.50 *

Pineapple 1.29 *

5)awk -F:‘{}‘

[root@localhost ~]# echo $PATH |awk -F: ‘{

> for(i=1;i<=NF;i++){

> printf "%s\n",$i;

> }

> }‘

/usr/local/software/mysql/bin

/usr/local/sbin

/usr/local/bin

/sbin

/bin

/usr/sbin

/usr/bin

/usr/local/software/erlang/bin

/root/bin

[root@localhost ~]# echo $PATH

/usr/local/software/mysql/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin

6)awk ‘条件{}‘ file

awk ‘$2>=1.0{printf "%s\t%s\n",$0,"Expensive";}‘  zdd.txt

t Price/lbs     Expensive

Kiwi 1.50       Expensive

Pineapple 1.29  Expensive

7)

awk ‘{printf "%-15s %s\n",$1,$2;}‘ zdd.txt

t               Price/lbs

Banana          0.89

Paech           0.79

Kiwi            1.50

Pineapple       1.29

Apple           0.99

8)awk ‘{OFS="";print }‘

[root@localhost ~]# echo "cat  wu sensation" | awk ‘{OFS="..";print $0}‘

cat  wu sensation

[root@localhost ~]# echo "cat  wu sensation" | awk ‘{OFS="..";$1=$1;print $0}‘         

cat..wu..sensation

[root@localhost ~]# echo "cat  wu sensation" | awk ‘{OFS="..";print $1,$2,$3}‘

cat..wu..sensation

[root@localhost ~]# echo "cat  wu sensation" | awk ‘{OFS="..";print $1,$2,$3,$4}‘

cat..wu..sensation..

9)getline

command |getline :将command 的结果赋值给$0

command |getline var:将command的结果赋值给var

10)

ARGC   命令行变元个数 

ARGV      命令行变元数组 

FILENAME   当前输入文件名 

FNR   当前文件中的记录号 

FS   输入域分隔符,默认为一个空格 

RS   输入记录分隔符 

NF   当前记录里域个数 

NR   到目前为止记录数 

OFS   输出域分隔符 

ORS      输出记录分隔符 

        11)打开外部文件

         awk ‘BEGIN{while(cat "/etc/passwd"|getline){print $0;};close("/etc/passwd")}‘

         awk ‘BEGIN{while(getline < "/etc/passwd"){print $0;};close("/etc/passwd")}‘

        12)

            Flag=abcd 

            awk ‘{print ‘$Flag‘}‘   结果为abcd 

            awk ‘{print  "$Flag"}‘   结果为$Flag


本文出自 “王尼美的成人之路” 博客,请务必保留此出处http://8335914.blog.51cto.com/8325914/1616947

awk 编程

标签:awk   linux   编程   nf   nr   onf   

原文地址:http://8335914.blog.51cto.com/8325914/1616947

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!