【问题标题】:how to print all lines in a file which has certain field less than some input value如何打印文件中某个字段小于某个输入值的所有行
【发布时间】:2019-07-19 07:24:03
【问题描述】:

我有一个文件 file_name,其行如下:

line1: Order='O1', ProductDetail: [Product='P1', Weight=100, Unit=Kg], ProductDetail: [Product='P2', Weight=90, Unit=Kg], ProductDetail: [Product='P3', Weight=110, Unit=Kg]
line2: Order='O2', ProductDetail: [Product='P1', Weight=100, Unit=Kg], ProductDetail: [Product='P2', Weight=100, Unit=Kg], ProductDetail: [Product='P3', Weight=110, Unit=Kg]

预期输出:

line1: Order='O1', ProductDetail: [Product='P1', Weight=100, Unit=Kg], ProductDetail: [Product='P2', Weight=90, Unit=Kg], ProductDetail: [Product='P3', Weight=110, Unit=Kg]

理想的预期输出:

line1: Order='O1', [Product='P2', Weight=90, Unit=Kg]

我需要打印重量小于 100 的任何产品的所有行。我将如何实现?

【问题讨论】:

  • 如果权重小于100,会从0开始吗?我的问题是字段 3 的长度总是还是 2 或 1? l
  • @EdMorton - 我添加了预期的输出。感谢分享链接

标签: shell awk sed grep cut


【解决方案1】:

awk 的另一种方式:

awk '
  {
  i = split ( $0 , a , /Weight=/ )
  for ( j = 2 ; j <= i ; j++ ) {
    sub ( /,.*/ , "" , a[j] )
    if ( a[j]+0 < 100 ) {
      print
      next
      }
    }
  }
' infile

【讨论】:

    【解决方案2】:

    一种不太可靠的方法是:

    $ awk -F'[ =,]' '{for(i=1;i<NF;i++) 
                        if($i=="Weight" && $(i+1)<100) 
                           {print; next}}' file
    
    line1: Order='O1', ProductDetail: [Product='P1', Weight=100, Unit=Kg], ProductDetail: [Product='P2', Weight=90, Unit=Kg], ProductDetail: [Product='P3', Weight=110, Unit=Kg]
    

    根据输入文件的结构设置分隔符,找到搜索标签“重量”并检查下一个字段中的值(由于=分隔符)。

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2019-07-01
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多