【问题标题】:awk cutting off when printing fields打印字段时 awk 中断
【发布时间】:2016-12-29 06:34:54
【问题描述】:

我无休止地搜索,找不到任何东西来解决这个看似非常简单的问题。

我有以下行读取 csv 文件并仅使用字段来创建新字符串。

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

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

每行的预期输出应该类似于“rating 应该是 1,id 应该是 1234”。

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

但这是我得到的输出:

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

我认为这是最简单的字符串连接的情况,但我对 awk 完全陌生,所以我很可能遗漏了一些明显的东西。我怎样才能让它打印我想要的字符串?

【问题讨论】:

  • @Inian 当然,对不起。添加了额外的信息。

标签: bash awk


【解决方案1】:

推荐使用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

【讨论】:

  • 工作了,谢谢,但你知道为什么我的打印输出会被截断吗?
  • @ssb:嗯,你有一个不平衡的双引号开始! printf 是我打印自定义字符串时的第一个想法,
  • 谢谢,不知道我需要在它的末尾添加双引号。
  • @ssb:基本上是整个print,用双引号括起来,分别用于$1$2,以扩大它们的价值。
  • “解决”问题的唯一原因是printf "%d" 将字符串$2<control-M> 转换为数字$2。如果您尝试将其打印为带有 %s 的字符串,问题仍然存在,因为问题是输入中的尾随 control-Ms,而不是输出打印。
【解决方案2】:

问题与您的 awk 脚本无关,它按原样很好。您的输入文件包含 control-M,请使用 dos2unix 或类似工具将其删除。

【讨论】:

  • 谢谢,我听说行尾是个问题。当我回到我的工作机器上时,我会验证这一点,如果是这样的话,将接受的答案切换到这个。
猜你喜欢
  • 2013-03-13
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
相关资源
最近更新 更多