简体   繁体   English

bash中的awk无法正常工作

[英]awk in bash not working

Code below is the simple version, but also illustrates the problem. 下面的代码是简单的版本,但也说明了问题。

Version does not work: 版本不起作用

df | awk -f <(cat - <<-'EOD'
{
    if(                                                                                                                                                                                       
        $1 == "tmpfs" ) {
            print $0;
        }
}
EOD
)

Version does work: 版本的工作:

df | awk -f <(cat - <<-'EOD'
{
    if( $1 == "tmpfs" ) {                                                                                                                                                                     
            print $0;
        }
}
EOD
)

the difference is how I place condition with if, the same line (works) or different lines (not working). 区别在于我如何在相同的行(有效)或不同的行(无效)下放置条件。 The production version has four long conditions, So I have to place them on different lines to make the code more readable. 生产版本具有四个较长的条件,因此我必须将它们放在不同的行上以使代码更具可读性。 Any one have came into this? 有人来过吗?

Just use escapes for end of line for your long if statement: 只要在长时间的if语句中使用转义符作为行的结尾:

df | awk -f <(cat - <<-'EOD'
{
    if ( \
        $1 == "tmpfs" ) {
            print $0;
        }
}
EOD
)

awk syntax evidently expects the if statement/expression to be on a single line. awk语法显然希望if语句/表达式在一行上。 In Unix/Linux it's common to be able to use the backslash () as a line continuation character. 在Unix / Linux中,通常可以使用反斜杠()作为行继续符。 So it will treat the above if ( \\ and the following line as if they were all on the same line syntactically. 因此,它将上面的if ( \\和下一行视为在语法上都位于同一行。

@mbratch answered your question, but as an aside, your posted script: @mbratch回答了您的问题,但顺便说一句,您发布的脚本:

df | awk -f <(cat - <<-'EOD'
{
    if( \
        $1 == "tmpfs" ) {
            print $0;
        }
    }
EOD
)

can/should be written as just this: 可以/应该这样写:

df | awk '$1 == "tmpfs"'

If you tell us what you're trying to do, we could probably help more. 如果您告诉我们您要做什么,我们可能会提供更多帮助。

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

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