awk使用

#将passwd文件每行重复打印10遍;while循环,当i>10时,结束循环。

[root@localhost linshi]# awk   '{i=1;while(i<=10){print $0;i++}}'  passwd
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash

#注释

[root@localhost linshi]# awk  -F:  '/^root/{i=1;while(i<=NF){print $i;i++}}'  passwd
root
x
0
0
root
/root
/bin/bash

#注释

[root@localhost linshi]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.170 test
52.87.94.70 registry-1.docker.io
[root@localhost linshi]# awk  -F:  '{i=1;while(i<=NF){print $i;i++}}' /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4


1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.170 test
52.87.94.70 registry-1.docker.io

#注释

[root@localhost linshi]# awk -F: '{i=1;while(i<=NF){printf "%-20s", $i;i++};print xxoo}' passwd

[root@localhost linshi]# awk -F: '{i=1;while(i<=NF){printf "%-20s", $i;i++};print }' passwd

 

awk中的for使用方式

二.循环语句(while,for,do)(转载)

1.while语句

格式:

while(表达式)

{语句}

例子:

[chengmo@localhost nginx]# awk 'BEGIN{ test=100; total=0; while(i<=test) {     total+=i;     i++; } print total; }' 5050

2.for 循环

for循环有两种格式:

格式1:

for(变量 in 数组)

{语句}

例子:

[chengmo@localhost nginx]# awk 'BEGIN{ for(k in ENVIRON) {     print k"="ENVIRON[k]; } }'

AWKPATH=.:/usr/share/awk OLDPWD=/home/web97 SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass SELINUX_LEVEL_REQUESTED= SELINUX_ROLE_REQUESTED= LANG=zh_CN.GB2312

。。。。。。

说明:ENVIRON 是awk常量,是子典型数组。

格式2:

for(变量;条件;表达式)

{语句}

例子:

[chengmo@localhost nginx]# awk 'BEGIN{ total=0; for(i=0;i<=100;i++) {     total+=i; } print total; }'

5050

原文地址:https://www.cnblogs.com/xiaofeng666/p/12354118.html