Linuxshell读取⼀⾏
⽅法⼀
通过指定IFS--Internal Field Separator,IFS默认情况下是<space><tab><newline>,可以在脚本中设定IFS值
DEMO 1
abcfd cat test_IFS.sh
#! /bin/sh
IFS="c"
for LINE in ``
do
echo LINE done sh test_IFS.sh
ab
fd
这⾥需要读取⼀⾏只需将IFS="\n"设置为换⾏符即可。
DEMO2
a b c d 不设置IFS cat test_IFS.sh
#! /bin/sh
#IFS="\n"
for LINE in ``
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 `` 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
linux换行按哪个键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 | 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
Processing math: 0%