shell逐行读取文件

14 篇文章 1 订阅

shell中如何逐行读取?

在ubuntu下测试。

准备2个文件:

$ cat cfg
line1_a line1_b
line2_a line2_b
line3_a line3_b$ cat cfg.newline 
line1_a line1_b
line2_a line2_b
line3_a line3_b

注:cfg最后一行是没有换行符的,cfg.newline最后一行是有换行符中。
hexdump -C cfghexdump -C cfg.newline两个命令对比可以发现,
cfg.newline最后是’0x0a’(换行符)。

shell脚本read_file.sh 如下:

#!/bin/bash
echo "FUNC: while read l"  # OK
while read l 
do 
echo "line :"$l
done < $1

echo "FUNC: cat while read l"  # OK
cat $1 | while read l 
do 
echo "line :"$l
done


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

echo "FUNC: while line"  # OK
while l=$(line)
do 
echo "line :"$l
done < $1

echo "FUNC: cat while line"  # OK
cat $1 | while l=$(line) 
do 
echo "line :"$l
done

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

echo "FUNC: for l in cat file"  # IN VAIN
for l in `cat $1`
do
echo "line:"$l"(end)"
done

echo "FUNC: for l in file"  # IN VAIN
for l in $(cat $1)
do
echo "line:"$l"(end)"
done

运行如下:

$ /bin/bash read_file.sh cfg
FUNC: while read l
line :line1_a line1_b
line :line2_a line2_b
FUNC: cat while read l
line :line1_a line1_b
line :line2_a line2_b
----------
FUNC: while line
line :line1_a line1_b
line :line2_a line2_b
FUNC: cat while line
line :line1_a line1_b
line :line2_a line2_b
----------
FUNC: for l in cat file
line:line1_a(end)
line:line1_b(end)
line:line2_a(end)
line:line2_b(end)
line:line3_a(end)
line:line3_b(end)
FUNC: for l in file
line:line1_a(end)
line:line1_b(end)
line:line2_a(end)
line:line2_b(end)
line:line3_a(end)
line:line3_b(end)

$ /bin/bash read_file.sh cfg.newline 
FUNC: while read l
line :line1_a line1_b
line :line2_a line2_b
line :line3_a line3_b
FUNC: cat while read l
line :line1_a line1_b
line :line2_a line2_b
line :line3_a line3_b
----------
FUNC: while line
line :line1_a line1_b
line :line2_a line2_b
line :line3_a line3_b
FUNC: cat while line
line :line1_a line1_b
line :line2_a line2_b
line :line3_a line3_b
----------
FUNC: for l in cat file
line:line1_a(end)
line:line1_b(end)
line:line2_a(end)
line:line2_b(end)
line:line3_a(end)
line:line3_b(end)
FUNC: for l in file
line:line1_a(end)
line:line1_b(end)
line:line2_a(end)
line:line2_b(end)
line:line3_a(end)
line:line3_b(end)

结论

1.
while read l 
do 
echo "line :"$l
done < $filename

cat $filename | while read l 
do 
echo "line :"$l
done

这种方式可以逐行读取文件,但不能读取没有换行符的最后一行。
且$l会去除该行前后所有空格,中间多个空格会换成1个空格。

2.
for l in `cat $1`
do
echo "line:"$l"(end)"
done

只能读取一个个空格或者换行分开的串,不是逐行读取。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值