有的时候, 循环文本如下
root@pts/1 # cat file |head -10
2961047 788934832 797699249 2018-01-30-10
2961054 801973977 797725431 2018-01-30-10
2961057 799438954 797701082 2018-01-30-10
2961064 802146497 797701082 2018-01-30-10
2961067 802146292 797351447 2018-01-30-10
2961074 802140219 801973274 2018-01-30-10
2961077 802132731 801134893 2018-01-30-10
2961082 802129091 797771835 2018-01-30-10
2961083 799350247 797487029 2018-01-30-10
2961097 800865188 797487029 2018-01-30-10
看似都在一行, 使用 for 循环处理是就会出问题, 我们来看下
root@pts/1 # for i in `cat file`;do echo $i ;done|head -10
2961047
788934832
797699249
2018-01-30-10
2961054
801973977
797725431
2018-01-30-10
2961057
799438954
每一行的信息分割后都到了下一行, 如果去截取字符串, 就会出问题, 我们可以使用 while read line 的方式处理
使用 while read line 读取文件时, line 的变量赋予如下
#!/bin/bash
cd /share/perdir/chaichuan/tmp
while read line
do
info=($line) ### 需要将读到的 line 赋予变量, 然后做字符串截取如 ${info[3]} 代表这行的第 4 个字符串
echo ${info[0]} ${info[1]} ${info[2]} ${info[3]}
done < file
root@pts/1 # bash temp.sh|head -10
2961047 788934832 797699249 2018-01-30-10
2961054 801973977 797725431 2018-01-30-10
2961057 799438954 797701082 2018-01-30-10
2961064 802146497 797701082 2018-01-30-10
2961067 802146292 797351447 2018-01-30-10
2961074 802140219 801973274 2018-01-30-10
2961077 802132731 801134893 2018-01-30-10
2961082 802129091 797771835 2018-01-30-10
2961083 799350247 797487029 2018-01-30-10
2961097 800865188 797487029 2018-01-30-10
可以直接使用 ${line[2]} 来截取需要的字符串
来源: http://www.bubuko.com/infodetail-2484875.html