shell之while read line二种用法

while read line

command | while read line;do command;done

  • read arg1 arg2 arg3 arg4 …,read是一個用來賦值的命令,它需要从目标输入获得值,然后把这些值按照位置依次赋值给变量arg1、arg2、arg3、arg4…,输入的时候以空格(可以有连续多个)作为分隔符

  • command命令的输出作为read循环的输入,这种结构长用于处理超过一行的输出,当然awk也很擅长做这种事

  • read通过输入重定向,把file的第一行所有的内容赋值给变量line循环体内的命令一般包含对变量line的处理;然后循环处理file的第二行、第三行....一直到file的最后一行。还记得while根据其后的命令退出状态来判断是否执行循环体吗?是的,read命令也有退出状态,当它从文件file中读到内容时,退出状态为0,循环继续惊醒;当read从文件中读完最后一行后,下次便没有内容可读了,此时read的退出状态为非0,所以循环才会退出

  • 在读取文件时,for i in cat xx.txt 或者 for i in $(<file.txt);do done 效率最高,while中while read line;do echo $line;done <test 效率最高

=============================================
# read 只有一个变量
[root@boy test]# cat line.txt 
12 xxxx sdfsadf
34 xx
[root@boy test]# cat test.sh 
#!/bin/bash
cat line.txt | while read line;  #";" 必须要加,否则有问题
do
	echo $line
done


# 执行结果,read 默认以空格(可以有很多个)来作为分割,将其分配给不同read后面的变量
[root@boy test]# bash test.sh 
12 xxxx sdfsadf
34 xx
===========================================================
# read 有二个变量
[root@boy test]# cat line.txt 
12 xxxx sdfsadf
34 xx
[root@boy test]# cat test.sh 
#!/bin/bash
cat line.txt | while read line1 line2;
do
	echo this is line1: $line1
	echo this is line2: $line2
done

# 执行结果
[root@boy test]# bash test.sh 
this is line1: 12
this is line2: xxxx sdfsadf
this is line1: 34
this is line2: xx
==============================================================
# read 有三个参数
[root@boy test]# cat line.txt 
12 xxxx sdfsadf
34 xx
[root@boy test]# cat test.sh 
#!/bin/bash
cat line.txt | while read line1 line2 line3;
do
	echo this is line1: $line1
	echo this is line2: $line2
	echo this is line3: $line3
done

# 执行结果,可以见由于第二行无法满足分配给三个变量,默认给第三个变量分配了"空"
[root@boy test]# bash test.sh 
this is line1: 12
this is line2: xxxx
this is line3: sdfsadf
this is line1: 34
this is line2: xx
this is line3:
"     空行      "

while read line;do echo $line;done < file

  • while中效率最高的,使用输入重定向的方式则每次只占用一行数据的内存,而且是在当前shell环境下执行的,while内的变量赋值、数组赋值在退出while后仍然有效
[root@boy test]# cat line.txt 
12    xxxx sdfsadf
34 xx
[root@boy test]# cat test.sh 
#!/bin/bash
while read line1 line2 line3 
do
	echo this is line1: $line1
	echo this is line2: $line2
	echo this is line3: $line3
done < line.txt


# 执行结果
[root@boy test]# bash test.sh 
this is line1: 12
this is line2: xxxx
this is line3: sdfsadf
this is line1: 34
this is line2: xx
this is line3:
"     空行         "
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺仔_牛奶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值