Shell三剑客:awk(awk编辑编程)三

一、For 循环

        For 循环的语法

for(variable addignment; condition; iteration peocess)
{
    statement1
    statement2
    ...
}
#for 语句首先执行初始化动作( initialisation ),然后再检查条件( condition )。如果条件为真,则执行动作( action ),然后执行递增( increment )或者递减( decrement )操作。只要条件为 true 循环
就会一直执行。每次循环结束都会进条件检查,若条件为 false 则结束循环。

        For 循环实例

#For 循环输出数字 1 至 5
[root@localhost ~]# awk 'BEGIN {for (i=1;i<=5;++i) print i}'
1
2
3
4
5

#For 循环输出数字 1 至 9 的奇数之和
[root@localhost ~]# echo "hello" | awk '
> {
> stotal =0
> for (i=1;i<10;i++)
>   {
>      if(i % 2 ==0)
>      {
>         continue
>      }
>      stotal =stotal + i
>    }
>    print "stotal=",stotal
> }'
stotal= 25

#将每行打印10次
[root@localhost ~]# awk -F: '{for(i=1;i<=10;i++) {print $0}}' /etc/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 ~]# awk -F: '{ for(i=1;i<NF;i++) {print $i}}' /etc/passwd
root
x
0
0
root
/root
bin
x
1
1
bin
/bin

 

二、While 循环

        While 循环的语法

while(condition)
{
    statement1
    statement2
    ...
}
#While 循环首先检查条件 condition 是否为 true ,若条件为 true 则执行动作 action。此过程一直重复直到条件 condition 为 flase 才停止。

        While 循环实例

#While 循环输出数字 1 到 5
[root@localhost ~]# awk 'BEGIN {i=1;while(i<6) {print i;++i}}'
1
2
3
4
5

#While 循环输出数字 1 至 9 的奇数之和
[root@localhost ~]# echo "hello" | awk '
> {
>    total=0
>    i=1
>    while(i<10)
>    {
>      if(i % 2==0)
>      {
>        i++
>        continue
>      }
>      total = total +i
>      i++
>    }
>    print "total=",total
> }'
total= 25

#打印第一行的前七列
[root@localhost ~]# awk -F: '/^root/{i=1;while(i<=7) {print $i;i++}}' /etc/passwd
root
x
0
0
root
/root
/bin/bash

#分别打印每行的每列
[root@localhost ~]# awk '{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

#将每行打印10次
[root@localhost ~]# awk -F: '{i=1;while(i<=10) {print $0;i++}}' /etc/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

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值