【问题标题】:Getting uniqe value from the first N characters [closed]从前 N 个字符中获取唯一值 [关闭]
【发布时间】:2018-11-23 10:35:57
【问题描述】:

虽然我之前一直在使用grep、uniq 和sort,但我不太明白如何解决我的问题。我非常感谢如何解决这个问题:)

我想从我的输入文件中获取前 6 个字符的 uniq,并得到如下所示的输出。我不知道是不是uniq,grep,awk我需要用,也许有人可以帮我一把。

我的文件如下所示:

Field1     Filed2    Field3
value1   some_stuff  something
value2   another     fake  
value1   fake        value    
value3   blah        blah
value2   blah        fake 


Prefered output:

Field1    Field2    Field3
value1   some_stuff something
value2   another    fake
value3   blah       blah

【问题讨论】:

  • 始终建议您在帖子@rockStar 中添加您的努力以及示例
  • 对不起,下次会添加它...退出 bz 做 atm 的东西:/

标签: awk grep uniq


【解决方案1】:

你可以试试关注吗,

awk 'FNR==1{print;next} !a[substr($0,1,6)]++' Input_file

说明:为上述代码添加说明。

awk '
FNR==1{                     ##Checking condition if line is first then do following.
  print                     ##Printing current line which is first line of headers.
  next                      ##next will skip all further lines from here.
}                           ##Closing condition BLOCK here.
!a[substr($0,1,6)]++        ##Creating array named a whose index is first 6 characters and keeping its increment value.
                            ##awk works on function condition/pattern and action, no action mentioned here so print of line happened.
'  Input_file               ##Mentioning Input_file name here.

如果您的第一个字段只有 6 个字符,请使用以下字符。

awk '!a[$1]++' Input_file

关于!a[$1]++ 部分。基本上它检查它是否已经存储在一个数组中(这里命名为x)上一行解析的第一列值。

如果是这种情况(a[$1] != 0),它不会输出该行。否则,它将输出并存储它(a[$1]++,因此a[$1] = a[$1] + 1 因此a[$1] 将等于1)用于下一行解析。看到这个Unix answer。

【讨论】:

  • thanx 这行得通,也为了解释,我保存了这个 oneliner,因为我会更频繁地使用它:)
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 2023-03-17
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多