当前位置: 技术问答>linux和unix
Awk读逗号分隔并带有空字段的文本
来源: 互联网 发布时间:2017-05-27
本文导语: A.txt的内容 11,123,,A,2014 Shell内容 awk -F“,” '{print $1,$2,$3,$4,$5}' A.txt | while read value1 value2 value3 value4 value5 do echo "a=${value1}" echo "b=${value2}" echo "c=${value3}" echo "d=${value4}" echo "e=${value5}" Done 运行后发现 ...
A.txt的内容
11,123,,A,2014
Shell内容
awk -F“,” '{print $1,$2,$3,$4,$5}' A.txt | while read value1 value2 value3 value4 value5
do
echo "a=${value1}"
echo "b=${value2}"
echo "c=${value3}"
echo "d=${value4}"
echo "e=${value5}"
Done
运行后发现
c=A
d=2014
e=空
求大神帮忙,让它们各归其位!第一次发帖,大家帮帮忙吧,搞IT的孕妈不容易呀
11,123,,A,2014
Shell内容
awk -F“,” '{print $1,$2,$3,$4,$5}' A.txt | while read value1 value2 value3 value4 value5
do
echo "a=${value1}"
echo "b=${value2}"
echo "c=${value3}"
echo "d=${value4}"
echo "e=${value5}"
Done
运行后发现
c=A
d=2014
e=空
求大神帮忙,让它们各归其位!第一次发帖,大家帮帮忙吧,搞IT的孕妈不容易呀
|
直接
cat a.txt | while IFS="," read value1 value2 value3 value4 value5
do
echo "a=${value1}"
echo "b=${value2}"
echo "c=${value3}"
echo "d=${value4}"
echo "e=${value5}"
done
就可以了吧
cat a.txt | while IFS="," read value1 value2 value3 value4 value5
do
echo "a=${value1}"
echo "b=${value2}"
echo "c=${value3}"
echo "d=${value4}"
echo "e=${value5}"
done
就可以了吧
|
提供一个解决方法,可以用,就是代码略别扭
#!/sbin/bash
#awk -F"," '{print $1,","$2,","$3,","$4,","$5}' a.txt
awk -F"," '{print $1,","$2,","$3,","$4,","$5}' a.txt | while IFS="," read value1 value2 value3 value4 value5
do
echo "a=${value1}"
echo "b=${value2}"
echo "c=${value3}"
echo "d=${value4}"
echo "e=${value5}"
done
|
楼主你看下这句awk -F“,” '{print $1,$2,$3,$4,$5}' A.txt的输出,单独执行,结果是11 123 A 2014。
明白了吧,在a.txt中,你的分隔符是,所有能识别空,但是你awk里print命令把输出结果用空格进行分割。
然后awk的结果管道传到read时,read不管你是一个空格还是多个空格,都忽略了。所以空值无法识别了。
至于解决方案,我在思考下,刚入门
明白了吧,在a.txt中,你的分隔符是,所有能识别空,但是你awk里print命令把输出结果用空格进行分割。
然后awk的结果管道传到read时,read不管你是一个空格还是多个空格,都忽略了。所以空值无法识别了。
至于解决方案,我在思考下,刚入门
|
$ echo "11,123, ,A,2014" | while IFS="," read value1 value2 value3 value4 value5
> do
> echo "a=${value1}"
> echo "b=${value2}"
> echo "c=${value3}"
> echo "d=${value4}"
> echo "e=${value5}"
> done
a=11
b=123
c=
d=A
e=2014
> do
> echo "a=${value1}"
> echo "b=${value2}"
> echo "c=${value3}"
> echo "d=${value4}"
> echo "e=${value5}"
> done
a=11
b=123
c=
d=A
e=2014