If you cant explain it simply, you dont understand it well enough

Linux shell 读取一行

 

Linux shell 读取一行

方法一

通过指定IFS--Internal Field SeparatorIFS默认情况下是<space><tab><newline>,可以下脚本中设定IFS

DEMO 1

$cat t1.txt 
abcfd   

$cat test_IFS.sh 
#! /bin/sh

IFS="c"

for LINE in `cat t1.txt`
do
     echo $LINE
done

$sh test_IFS.sh 
ab
fd

这里需要读取一行只需将IFS="\n"设置为换行符即可。

DEMO2

$cat t1.txt 
a b
c d

不设置IFS

$ cat test_IFS.sh 
#! /bin/sh

#IFS="\n"

for LINE in `cat t1.txt`
do
    echo $LINE
done

$sh test_IFS.sh 
a
b
c
d

设置IFS="\n"

$ cat test_IFS.sh 
#! /bin/sh

IFS="\n"

for LINE in `cat t1.txt`
do
    echo $LINE
done

$sh test_IFS.sh 
a b
c d

这样就可以达到读取一行的目的了

方法2

利用read命令,从标准输入读取一行,根据IFS进行切分并相应的变量赋值,这里为了我们故意将IFS设置为&,来进行演示

DEMO3

$cat test_read.sh 
#! /bin/sh

IFS="&"
printf "Enter your name, rank, serial num:"
read name rank serno

printf "name=%s\nrank=%s\nserial num=%s" $name $rank $serno 

$sh test_read.sh 
Enter your name, rank, serial num:zk&1&123
name=zk
rank=1
serial num=123

所以我们知道read每次是读一行,因此使用read命令就好了

DEMO4

$cat readline_1.sh 
#! /bin/sh

cat t1.txt | while read LINE
do
    echo $LINE
done

$sh readline_1.sh 
a b
c d

这里是通过文件重定向给read处理

方法3

read去读取文件重定向

DEMO5

$cat readline_2.sh 
#! /bin/sh

while read LINE
do
    echo $LINE
done < t1.txt

$sh readline_2.sh 
a b
c d

推荐使用方法3

 

posted @ 2014-08-11 17:17  zk47  阅读(4291)  评论(0编辑  收藏  举报

I am a stupid bird, and I need to work hard