从给定文件中读取第二列时 在使用awk从给定文件中读取多列时,我遇到了问题。 读取第2列时,内容向右移动。
/home/Binay/bin] 82#head -2 /data/xyz/serial/fep_xyz/temp/./xyz_reject_file_details_20180926194730.dat
309_body_mass_index_at_refresh.ABORT.2018-05-13.dat_SKIP_AT|Failed MBR_KEY Lookup|94
309_disease_management_member_activity_at_refresh.ABORT.2018-05-13.dat_SKIP_AT|Failed MBR_KEY Lookup|11575
/home/Binay/bin] 82#
预期输出
/home/Binay/bin] 82# cat /data/xyz/serial/fep_xyz/temp/./xyz_reject_file_details_20180926194730.dat | awk -F'|' ' {print $1,$2,$3} ' | while read abort_file abort_reason record_count <
> do
> echo ${abort_reason}
> done
Failed MBR_KEY Lookup
Failed MBR_KEY Lookup
/home/Binay/bin] 83#
但是我目前得到的输出为
/home/Binay/bin] 82# cat /data/xyz/serial/fep_xyz/temp/./xyz_reject_file_details_20180926194730.dat | awk -F'|' ' {print $1,$2,$3} ' | while read abort_file abort_reason record_count <
> do
> echo ${abort_reason}
> done
Failed
Failed
/home/Binay/bin] 83#
答案 0 :(得分:1)
while IFS='|' read -r abort_file abort_reason record_count; do echo ${abort_reason}; done < filename
为什么不在while期间直接使用输入字段分隔符?
答案 1 :(得分:1)
您的第二个字段包含空格。最初的awk脚本的作用基本上是用空格替换字段分隔符,因此$abort_reason
成为行上第二个用空格分隔的单词。观察:
$ cat y.dat
a_b_c|two words|123
one_two|more words|234
$ awk -F'|' '{print $1,$2,$3}' y.dat
a_b_c two words 123
one_two more words 234
$ awk -F'|' '{print $1,$2,$3}' y.dat | while read a b c; do echo "$b"; done
two
more
仅使用bash并填充数组以简化管理:
$ while IFS='|' read -a a; do declare -p a; done < y.dat
declare -a a=([0]="a_b_c" [1]="two words" [2]="123")
declare -a a=([0]="one_two" [1]="more words" [2]="234")
如果您确实想使用awk进行字段拆分,则需要确保您的输出在字段中间不包含字段分隔符。例如:
$ awk -F'|' '{gsub(/ /,"_"); print $1,$2,$3}' y.dat
a_b_c two_words 123
one_two more_words 234
$ awk -F'|' '{gsub(/ /,"_"); print $1,$2,$3}' y.dat | while read red green blue; do echo "$green"; done
two_words
more_words