2016-12-29 84 views
1

我已经无休止地搜索了,找不到任何东西来解决看起来像是一个非常简单的问题。awk在打印字段时切断

我有以下行读取csv文件,只是使用字段来创建一个新的字符串。

的输入是一个简单的2列组整数:

1234,1 
5678,2 
1357,5 
2468,4 

每个预期的输出应该类似“的评级应该是1和id应该是1234”的每一行。

awk -F "," '{print "rating should be "$2" and id should be "$1}' $1 >> $FILENAME 

但这是输出I得到:

and id should be 635277 
and id should be 29894 
and id should be 576076 

我认为这是最简单的字符串连接的情况下,但我完全陌生的awk的,所以我很可能会丢失一些明显的事我怎样才能得到这个打印我想要的字符串?

+0

@Inian当然,对不起。增加了额外的信息。 – ssb

回答

1

的问题无关,与你的awk脚本这是很好的原样。您的输入文件包含control-Ms,使用dos2unix或类似命令将其删除。

+0

谢谢,我听说行结束是一个问题。当我回到工作机器上时,我会验证这一点,如果情况如此,请将接受的答案转换为此。 – ssb

2

推荐使用printf来打印带引号的字符串,这是POSIX兼容并且跨平台可用。

awk -F"," '{printf "rating should be %d and id should be %s\n", $2,$1}' input-file 
rating should be 1 and id should be 1234 
rating should be 2 and id should be 5678 
rating should be 5 and id should be 1357 
rating should be 4 and id should be 2468 

从你print例如修理你无端接双引号字符串,解决了这个问题对我来说

awk -F "," '{print "rating should be "$2" and id should be "$1""}' input-file 
rating should be 1 and id should be 1234 
rating should be 2 and id should be 5678 
rating should be 5 and id should be 1357 
rating should be 4 and id should be 2468 
+0

工作过,谢谢,但是你知道我为什么用打印得到中断输出吗? – ssb

+0

@ssb:那么你有一个不平衡的双引号开始! 'printf'是我的第一个想法,当涉及到打印自定义字符串时, – Inian

+0

@ssb:请参阅我的更新,了解如何修复它 – Inian