【问题标题】:compare multiple fields in awk比较awk中的多个字段
【发布时间】:2022-01-01 00:12:13
【问题描述】:

我有一个文件,其中存在属性值对列表。该文件如下所示:

% cat file2.txt 
"a b c" 1
"d e" 2

代码将需要查找属性并在找到时增加值。我最初使用的是单个单词属性,下面的代码运行良好。现在需求变了,属性可以是带有数字、特殊字符和双引号的多字。

#This works only if attribute is single word
% cat file1.txt 
abc 1
def 2
% var=abc
% awk -v p="$var" '$1~p {$2+=1}; {print}' file1.txt
abc 2
def 2

既然属性不仅是第一个字段而且可以是任何大小,我如何才能让它工作?我想知道是否有办法用 awk 做到这一点。

谢谢

编辑:

这是我期望的输出:

#This is file2.txt initially:

% cat file2.txt 
"a b c" 1
"d e" 2

#I should be able to execute the code passing var="a b c" on file2.txt and i am expecting the below output:

"a b c" 2
"d e" 2

【问题讨论】:

  • 每行的最后一个字段是如果该行的其余部分匹配则需要增加的值
  • 您是否尝试连接除最后一个字段之外的所有字段,然后比较该连接的字符串?还要考虑sort < file | uniq -c是否可以做你想做的事。
  • 为什么要使用“linux”、“bash”和“shell”标签?请不要那样做,还要阅读这些标签的描述!
  • 谢谢 Ed,你是对的。我已经编辑了问题。

标签: awk script


【解决方案1】:
$ cat file2.txt 
"a b c" 1
"d e" 2

$ var=c

$ awk -v p="$var" '{ for (i=1; i<NF; i++) if ($i ~ p) $NF +=1; print }' file2.txt
"a b c" 2
"d e" 2

【讨论】:

    【解决方案2】:

    如果我正确理解您的要求,请尝试一下:

    % cat file2.txt
    "a b c" 1
    "d e" 2
    fg 3
    % var="abc"
    % awk -v p="$var" '
    {
        num = $NF                                           # value of the last field
        if (match($0, /"[^"]+"/)) {                         # if the attribute is enclosed with double quotes
            attr = substr($0, RSTART + 1, RLENGTH - 2)      # extract the enclosed substring as attr
            gsub(" ", "", attr)                             # pack attr by removing whitespaces
        } else {
            attr = $1                                       # if the double quotes are not present, pick the 1st field
        }
        if (match(attr, p)) num++                           # increment num if attr matches p
        print attr, num     
    }' file2.txt
    abc 2
    de 2
    fg 3
    

    【讨论】:

      【解决方案3】:
      $ var="a b c"
      $ awk -v var="\"$var\"" 'index($0,var)==1{$NF++} 1' file2.txt
      "a b c" 2
      "d e" 2
      

      【讨论】:

        猜你喜欢
        • 2014-12-25
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 2022-01-08
        • 1970-01-01
        • 2023-03-27
        • 2011-10-30
        • 1970-01-01
        相关资源
        最近更新 更多