变量中的awk运算符

变量中的awk运算符

本文介绍了变量中的awk运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文件

cat file1.txt
lspol > 8296
....
cat file2.txt
lspol 8297
...

如果文件2.txt中第1列的编号大于文件1.txt中第1列的编号,我尝试获取输出

I am trying to get output if the number for column 1 in file2.txt is greater than number in for column 1 in file1.txt

下面的命令很好用

# if column 1 of file1.txt is equal to column 1 of file2.txt and column 3 of file1.txt is greater than column 2 in file2.txt
awk '
   {
       getline buf <f2;
       split( buf, a, " " );
       if( $1 == a[1]  && $3+0 > a[2]+0 )
           printf( "%s\n", buf );
   }
' f2="file2.txt" file1.txt

我试图将运算符从file1.txt的第二列中拉出,但是没有运气.我尝试了很多方法,这是其中之一

I am trying to pull the operator from 2nd column in file1.txt but no luck. I have tried many ways and here is one of them

awk '
   {
       getline buf <f2;
       split( buf, a, " " );
       if( $1 == a[1]  && $3+0 $2 a[2]+0 )
           printf( "%s\n", buf );
   }
' f2="file2.txt" file1.txt

推荐答案

使用未经验证的输入总是有风险的,但我认为这可能是您要尝试执行的操作:

Using unvalidated input is always risky but I THINK this might be what you're trying to do:

$ cat tst.awk
NR==FNR {
    ops[$1] = $2
    vals[$1] = $3
    next
}
{ comparison = sprintf("%d %s %d", $2, ops[$1], vals[$1]) }
system("awk \047BEGIN{exit} END{exit (" comparison ")}\047")
$ awk -f tst.awk file1 file2
lspol 8297

每行末尾的数字值已经是安全的,因为如果它们还不是数字,则将它们专门转换为数字,您可以使用以下方法使操作员安全:

The numeric values at the end of each line are already safe as they're specifically being converted to numbers if they weren't already numbers and you can make the operator safe with:

$ cat tst.awk
NR==FNR {
    if ( $2 ~ /^[!<>=~]{1,2}$/ ) {
        ops[$1]  = $2
        vals[$1] = $3
    }
    else {
        print "Bad operator:", $2 | "cat>&2"
        exit 1
    }
    next
}
{ comparison = sprintf("%d %s %d", $2, ops[$1], vals[$1]) }
system("awk \047BEGIN{exit} END{exit (" comparison ")}\047")

或其他类似的regexp用于您要支持的比较运算符.

or some other such regexp for whatever comparison operators you want to support.

上面的欺骗是因为它没有在1个awk命令中对运算符进行求值,而是使用awk通过子shell调用awk来评估要测试的表达式.鉴于此,它将比在1 awk命令中对比较进行硬编码要慢几个数量级.

The above cheats as it's not evaluating the operator within 1 awk command, instead it's using awk to call awk through a subshell to evaluate the expression you want tested. Given that, it will be orders of magnitude slower than hard-coding the comparisons within 1 awk command.

有关类似的脚本,另请参见 https://stackoverflow.com/a/54161251/1745001 .

See also https://stackoverflow.com/a/54161251/1745001 for a similar script.

如果这不是您要尝试的操作,请编辑您的问题以阐明您的要求,并提供更真实的代表性示例输入/输出.

If that's not exactly what you're trying to do then edit your question to clarify your requirements and provide more truly representative sample input/output.

这篇关于变量中的awk运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:44