【问题标题】:Find a variable length number inside a string from a file using awk?使用awk从文件中查找字符串中的可变长度数字?
【发布时间】:2018-07-02 03:01:57
【问题描述】:

我在 UNIX 上有很多文件,并希望在该文件中获取与指定模式关联的数字。

大部分文件将在文件中具有独特的模式,如下所示

some text abc
some text abc
some text abc
(3 rows)

我只想使用 awk 打印数字 3

数字可能因文件而异,可以是 35644 或任何数值。

我想使用 awk 而不是 sed 或 grep 来查找该数字,因为 HP unix 不支持高级 sed/grep 功能。

【问题讨论】:

  • 行是连续的,还是可以有不同的行?
  • 对于这种简单的情况不需要高级的 sed/grep(基本的 sed 就足够了)。 我只想打印数字 - 也只有数字或文件名?
  • 最后一行总是(number rows) 文本。文件中的行可能会有所不同,但总会有(number rows) 这样的模式。
  • @RomanPerekhrest 我在不支持 sed -i 的 HP unix 上,因此我不想在 sed 中进行高级分组,因为它不起作用。

标签: bash unix awk text-processing


【解决方案1】:

以下内容对您有用吗?

sed -e 's/(\([0-9][0-9]*\) rows)/\1/;t;d'

如果(N rows)N 替换成功,t 进入脚本末尾,否则d 删除该行(即所有不包含该表达式的行都将被跳过) .

【讨论】:

    【解决方案2】:

    由于您不想(或不能)使用简单的 sed 方法,这里是 awk 解决方案:

    示例输入文件:

    $ head file[123]
    ==> file1 <==
    some text abc
    some text abc
    some text abc
    (3 rows)
    
    ==> file2 <==
    some text abc
    some text abc
    some text abc
    some text abc
    some text abc
    (5 rows)
    
    ==> file3 <==
    some text abc
    some text abc
    (2 rows)
    

    $ for f in file[123]; do awk 'END{ print FILENAME, substr($1, 2) }' "$f"; done
    file1 3
    file2 5
    file3 2
    

    sed 解决方案(在我的变体中)将如下所示:

    for f in file[123]; do echo -n "$f "; sed -n '$ s/[() ]\|rows//gp' "$f"; done
    

    【讨论】:

      【解决方案3】:

      也许用这个 awk

      awk -v RS='(' 'END{print $1}' infile
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-27
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-28
        相关资源
        最近更新 更多