Chinaunix
标题:
read line读固定格式文本,字段错位
[打印本页]
作者:
xdsheng
时间:
2014-09-22 15:22
标题:
read line读固定格式文本,字段错位
本帖最后由 xdsheng 于 2014-09-22 15:38 编辑
test.txt内容如下:
1|test1|over1
2|test2|over2
3| |over3
4| |over4|
test.sh内容如下:
IFS='|'
echo " cat file whiel read line"
cat test.txt |while read line
do
a=`echo $line | awk '{print $1}'`;
b=`echo $line | awk '{print $2}'`;
c=`echo $line | awk '{print $3}'`;
d=`echo $line | awk '{print $4}'`;
echo "a="$a "b="$b "c="$c "d="$d
done
执行test.sh结果如下:
cat file whiel read line
a=1 b=test1 c=over1 d=
a=2 b=test2 c=over2 d=
a=3 b=over3 c= d=
a=4 b=over4 c= d=
期望结果:
cat file whiel read line
a=1 b=test1 c=over1 d=
a=2 b=test2 c=over2 d=
a=3 b= c=over3 d=
a=4 b= c=over4 d=
问:如何解决?
作者:
Shell_HAT
时间:
2014-09-22 15:59
while read line; do
a=`echo $line | awk -F '|' '{print $1}'`
b=`echo $line | awk -F '|' '{print $2}'`
c=`echo $line | awk -F '|' '{print $3}'`
d=`echo $line | awk -F '|' '{print $4}'`
echo "a=$a b=$b c=$c d=$d"
done < test.txt
复制代码
作者:
yestreenstars
时间:
2014-09-22 16:02
直接用awk最方便了
awk -F\| '{printf "a=%s b=%s c=%s d=%s\n",$1,$2,$3,$4}'
复制代码
作者:
o789789
时间:
2014-09-22 16:04
vi test2.sh
#!/bin/bash
num=`cat test.txt |wc -l`
for name in `seq 1 $num`
do
a=`cat test.txt |sed -n "$name"p |awk -F"|" '{print $1}' `
b=`cat test.txt |sed -n "$name"p |awk -F"|" '{print $2}' `
c=`cat test.txt |sed -n "$name"p |awk -F"|" '{print $3}' `
d=`cat test.txt |sed -n "$name"p |awk -F"|" '{print $4}' `
echo "a=$a b=$b c=$c d=$d"
done
作者:
xdsheng
时间:
2014-09-22 16:25
其实我已经申明了分隔符 IFS='|',这样写法还是不行的
回复
2#
Shell_HAT
作者:
xdsheng
时间:
2014-09-22 16:27
{:3_187:} 你的回答亲测成功,谢谢,咱交个朋友吧!大神{:3_187:}
回复
4#
o789789
作者:
xdsheng
时间:
2014-09-22 16:58
哥么,你的答案也是正确的{:3_189:}
回复
2#
Shell_HAT
作者:
bulletmarquis
时间:
2014-09-22 17:05
回复
7#
xdsheng
LZ这个ID的注册时间和发贴数。。。
作者:
xdsheng
时间:
2014-09-25 10:14
矮,这都是细节
回复
8#
bulletmarquis
作者:
bulletmarquis
时间:
2014-09-25 10:34
回复
9#
xdsheng
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2