简体   繁体   English

奇怪的awk行为,打印了$ 1,但没有打印$ 0?

[英]Weird awk behaviour , $1 is printed but $0 is not?

This is printed fine ls | xargs -I var sh -c 'echo var | awk "{print $1}"' 这是印刷好的ls | xargs -I var sh -c 'echo var | awk "{print $1}"' ls | xargs -I var sh -c 'echo var | awk "{print $1}"'

while this is not ls | xargs -I var sh -c 'echo var | awk "{print $0}"' 虽然这不是ls | xargs -I var sh -c 'echo var | awk "{print $0}"' ls | xargs -I var sh -c 'echo var | awk "{print $0}"'

Obviously this is not my use case and is just to reproduce the problem. 显然,这不是我的用例,只是重现了问题。

So while $0 stands for complete line, it is weird for $0 to not print while $1 gets printed. 因此,虽然$ 0代表整行,但$ 0被打印却不打印$ 0是很奇怪的。

Reference OS - Ubuntu 14.04 参考操作系统-Ubuntu 14.04

When you use: 使用时:

ls | xargs -I var sh -c 'echo var | awk "{print $0}"'

That has $0 in double quotes hence $0 gets expanded by shell which is in this case has value sh without quotes. 那有$0的双引号,因此$0被shell扩展了,在这种情况下,它的值sh没有引号。 awk treats it as a variable and prints blank. awk将其视为变量并打印空白。

To make it work escape the $ : 为了使它转义$

ls | xargs -I var sh -c 'echo var | awk "{print \$0}"'

Why $1 works: 为什么$1有效:

ls | xargs -I var sh -c 'echo var | awk "{print $1}"'

$1 also gets expanded by shell and it is empty. $1也由shell扩展,并且为空。 Hence awk just executes an empty print which is equivalent of print $0 and you get filename in output. 因此, awk只会执行一个空print ,该print等效于print $0 ,您将在输出中获得filename。

However it is not a good idea to use awk command in double quotes and parsing ls output is error prone. 但是,在双引号中使用awk命令不是一个好主意,并且解析ls输出容易出错。

For others landing here: If your syntax was perfect but you are potentially using windows files, remember the \\r will effectively overwrite your text and make it seem like $0 is blank.... 对于其他登陆此处的用户:如果语法完美,但是您可能正在使用Windows文件,请记住\\r将有效覆盖您的文本,并使其看起来像$0是空白...。

First run dos2unix <file> , then try your awk . 首先运行dos2unix <file> ,然后尝试使用awk

Note: removing \\r with sed or tr isn't enough 注意:用sedtr删除\\r是不够的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM