[英]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 注意:用
sed
或tr
删除\\r
是不够的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.