【问题标题】:Create array from output of command that is newline delimited and contains spaces [duplicate]从以换行符分隔并包含空格的命令输出创建数组[重复]
【发布时间】:2017-11-08 23:14:09
【问题描述】:

有很多类似的问题,但我找不到能解决我的问题的问题。可能我不知道该谷歌什么。

我正在尝试创建一对数组,然后按索引循环遍历这两个数组。数组的内容是从这个命令生成的:

$ cat small | grep -Po "(?<=Query: ).+$" | grep -v "use"

select count(*) from batting_small
select count(*) from batting_small_parquet
select count(*) from batting_small_parquet_stats
select yearid, count(*) from batting_small_parquet group by yearId
select yearid, count(*) from batting_small_parquet_stats group by yearId
select min(hr), max(hr) from batting_small
select min(hr), max(hr) from batting_small_parquet
select min(hr), max(hr) from batting_small_parquet_stats
...

但是制作这样的数组

queries=( ` cat small | grep -Po "(?<=Query: ).+$" | grep -v "use" ` )

按单词而不是按行拆分。如何按行拆分?

【问题讨论】:

  • 看起来你分析mysql慢日志文件,为此目的在mysql包中有一个特殊的例程mysqldumpslow,我认为它可以做很多你想要的。 mysqldumpslow --help
  • 它们不是 mysql 日志,但感谢您提供可能的替代方案

标签: arrays bash


【解决方案1】:

使用mapfile bash 内置,并从进程替换重定向 grep 命令:

mapfile -t queries < <( grep -Po "(?<=Query: ).+$" small | grep -v "use")

【讨论】:

    【解决方案2】:

    您可以在grep 中使用-z 选项来产生一个NUL 终止的输出,然后在while IFS= read -d '' 循环中使用进程替换:

    while IFS= read -d '' -r line; do
       echo "<<$line>>"
    done < <(ggrep -zPo '(?m)(?!.*use)(?<=Query: ).+$' small)
    
    <<select count(*) from batting_small>>
    <<select count(*) from batting_small_parquet>>
    <<select count(*) from batting_small_parquet_stats>>
    <<select yearid, count(*) from batting_small_parquet group by yearId>>
    <<select yearid, count(*) from batting_small_parquet_stats group by yearId>>
    <<select min(hr), max(hr) from batting_small>>
    <<select min(hr), max(hr) from batting_small_parquet>>
    <<select min(hr), max(hr) from batting_small_parquet_stats>>
    

    echo "&lt;&lt;$line&gt;&gt;" 行更改为您的实际代码。

    还要注意使用(?m) 在正则表达式中启用MULTILINE 模式,并使用负前瞻(?!.*use) 来避免另一个grep -v

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 2014-05-11
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多