• Post author:
  • Post category:shell
  • Post comments:0评论

1、while

[root@cp3 scripts]# cat a.txt 
aaa 111
bbb 222
ccc 333

[root@cp3 scripts]# cat line.sh 
#!/bin/bash
# 1、read+重定向
while read line;do
  echo $line
done < /scripts/a.txt

echo "---------------------"

# 2、read+管道
cat /scripts/a.txt | while read line;do
  echo $line
done

echo "---------------------"

# 3、read+管道(变量)
a=`cat /scripts/a.txt`
echo "$a" | while read line;do
  echo $line
done

[root@cp3 scripts]# bash line.sh 
aaa 111
bbb 222
ccc 333
---------------------
aaa 111
bbb 222
ccc 333
---------------------
aaa 111
bbb 222
ccc 333

2、for

  for 循环读行操作和while读行的是有很大区别的。while是完全按行读取,不管行内有啥,而for虽然也是按行读取,如果行内文字有空格或者制表,则会分开读取的。如下:

[root@cp3 scripts]# cat a.txt 
aaa 111
bbb 222
ccc 333
ddd444

[root@cp3 scripts]# cat line.sh 
#!/bin/bash
for line in `cat a.txt`;do
  echo $line
done

[root@cp3 scripts]# bash line.sh 
aaa
111
bbb
222
ccc
333
ddd444

这是因为 for 是按分内部域分隔符(IFS)来识别行的,所以我们可以定义分隔符来做到按行读取:

[root@cp3 scripts]# cat a.txt 
aaa 111
bbb 222
ccc 333
ddd444

[root@cp3 scripts]# cat line.sh 
#!/bin/bash
IFS=$'\n'
for line in `cat a.txt`;do
  echo $line
done

[root@cp3 scripts]# bash line.sh 
aaa 111
bbb 222
ccc 333
ddd444

注意定义 IFS 变量的写法:

IFS='\n'        # 这样写,分隔符就为字符 n 了。
IFS=$"\n"       # 这里\n确实通过$转化为了换行符,但仅当被解释时(或被执行时)才被转化为换行符。
IFS=$'\n'       # 正确写法,分隔符为换行符

发表回复

验证码: + 85 = 94