【问题标题】:awk iterating through an array using for loop and printing based on if conditionawk 使用 for 循环遍历数组并根据 if 条件打印
【发布时间】:2014-01-17 06:01:39
【问题描述】:
   bash --version

bash --version GNU bash,版本 3.2.25(1)-release (x86_64-redhat-linux-gnu) 版权所有 (C) 2005 Free Software Foundation, Inc.

cat 文件名.txt|cut -d "|" -f1|tr -d [^:digit:][:punct:]
[:blank:]|tail -10|awk '{a[i++]=$0;}{k=length(a)}END{for (i=k;i>=1;i--)if (5==5){print i " "a[i]" " a[i-1]" "k}}'

10            10
9  18410      10
8 18410 18409 10
7 18409 18408 10
6 18408 18407 10
5 18407 18406 10
4 18406 18405 10
3 18405 18404 10
2 18404 18403 10
1 18403 18402 10


cat filename.txt|cut -d "|" -f1|tr -d [^:digit:][:punct:]   [:blank:]|tail -10|awk '{a[i++]=$0;}{k=length(a)}END{for (i=k;i>=1;i--)if ((a[i]-1)==a[i-1]){print i " "a[i] " "k} else print "not done"}'

not done
not done
not done
not done
not done
not done
not done
not done
not done
not done

如果前面的数字比x 小一,则尝试获取最大的数字x

wc -l 没有给出我需要的行数。我不需要行数。

使用cut 提取的列是此 csv 文件中的主键。 文件末尾可能有未知数量的空行。

 cat filename.txt|cut -d "|" -f1|tr -d [^:digit:][:punct:]    [:blank:]|tail -10
18402
18403
18404
18405
18406
18407
18408
18409
18410

为什么这是 if 条件评估以采取“其他操作”? (a[i]-1==a[i-1]) 评估为假。我不明白为什么。

【问题讨论】:

  • 不清楚您的问题是什么,您能否更明确地说明您想要实现的目标?
  • 我正在尝试从我的管道分隔文件中获取行数,这就是文件的样子 cat filename.txt|cut -d "|" -f1|tr -d [^:digit:][:punct:][:blank:]|tail -10 18402 18403 18404 18405 18406 18407 18408 18409 18410
  • 现在有意义吗?也许我错过了一些愚蠢的事情。
  • 你确定它不起作用吗?我只为第一个字符串得到not done
  • 我的tr 版本无法识别[^:digit:] 中的插入符号..

标签: arrays if-statement for-loop awk cut


【解决方案1】:

给定以下 CSV 文件 (filename.txt):

1a|b|123
2a|b|123
3|4
5.7|4
66
67
10|11
11|aaa

我们可以使用以下方法确定数字 67:

awk -f s.awk filename.txt

s.awk 在哪里:

BEGIN {
    FS="|"
}
NF>=1 {
    q=$1
    gsub(/([^[:digit:]])|([[:blank:][:punct:]])*/,"",q)
    if (q==(prev+1))
        if (q>max)
            max=q
    prev=q
}
END {
    print "Max=" max
}

更新

单线可能看起来像:

awk 'BEGIN { FS="|" } { q=$1; gsub(/([^[:digit:]])|([[:blank:][:punct:]])*/,"",q); if (q==(prev+1)) {if (q>max) max=q} prev=q } END { print "Max=" max }' filename.txt

【讨论】:

  • 需要单线,不过感谢您的回复。
  • 这行得通!我认为 awk 对于大文件来说是残废的,使它在我写的一行中只循环了十行,无论如何这不起作用,这个现在可以工作,但必须测试它谢谢
  • @user3146086 太好了!
  • @user3146086 是的,我无法将讨论转移到 stackoverflow 聊天中,因为您的声誉太小了.. :)
  • @user3146086 我有一个问题要问您:您的第一个字段实际上是什么样的?是否需要在gsub(/([^[:digit:]])|([[:blank:][:punct:]])*/,"",q) 中进行所有替换?
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 2012-06-04
  • 2020-05-31
相关资源
最近更新 更多