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
原文地址:http://8335914.blog.51cto.com/8325914/1616947