awk printf 的意外输出

awk printf 的意外输出

我有以下 csv 文件:

$ cat mycsv.csv 
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12”,”A”,”N”  
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12”,”A”,”N”  
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12”,”A”,”N”  

为什么以下不打印所有行?

$awk -F "," '{printf}' mycsv.csv    
 ","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12”,”A”,”N””  

$awk -F "," '{printf $0}' mycsv.csv 
 ","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12”,”A”,”N””  

两者都应该打印所有行,对吗?我究竟做错了什么?

答案1

的第一个参数printf,无论是 Cprintf()还是printf实用程序 or awk'sprintf()都需要1并且是格式

你要:

awk '{printf "%s", $0}'

这里。如果你不需要输出记录分隔符,你也可以这样做:

awk -v ORS= '{print}' < mycsv.csv

甚至:

awk -v ORS= 1 < mycsv.csv

({print}是默认操作,真的是默认条件,但您需要指定至少一个操作或条件,1这是一种说法真的)。

虽然在这里,tr就足够了:

tr -d '\n' < mycsv.csv

或者如果你还想要尾随换行符,以便输出仍然是文本:

paste -sd '\0' mycsv.csv

您的文件似乎还具有 Microsoft 风格的 CRLF 行分隔符,因此您可能还想删除 CR 字符:

tr -d '\r\n' < mycsv.csv

awk或者仅使用支持多个单字符的实现的 CRLF 序列RS(包括gawkmawk不包括 macOS awk):

awk -v RS='\r\n' -v ORS= 1 < mycsv.csv

或者:

awk -v RS='\r?\n' -n ORS= 1 < mycsv.csv

即可以\r选择处理 Unix 或 MS-DOS 行分隔符。

或者先使用dos2unix或 之类的东西d2u将文件转换为 Unix 格式。

笔记

1格式参数printf是必需的awk公用事业的标准规范。输入gawkmawk省略它会导致错误。在 中busybox awk,它相当于从原始实现派生出来的(如 on printf ""),它相当于(没什么用处,因为它仍然被视为一种格式,如果包含字符,您仍然会收到错误)。awkmacOSprintf $0$0%

相关内容