【问题标题】:Split, find and iterate over output of command拆分、查找和迭代命令的输出
【发布时间】:2021-10-02 10:47:27
【问题描述】:

我目前有以下 bash 命令:

cargo metadata | jq .workspace_members[]

它返回如下内容:

"module1 0.1.0 (path+file:///workspace/module1)"
"module2 0.1.0 (path+file:///workspace/nested/module2)"
"module3 0.1.0 (path+file:///workspace/nested/module3)"

我想用新行分割字符串/流/输入并找到(使用正则表达式path\+file\:(.*)\))每行的文件路径。然后能够迭代它们:

for path in strings; do
   echo "$path"
done

然后打印出路径:

///workspace/module1
///workspace/nested/module2
///workspace/nested/module3

【问题讨论】:

    标签: bash shell jq


    【解决方案1】:

    您可以仅使用jq 提取路径,并使用基于正则表达式的match 过滤器:

    $ cargo metadata | jq -r '.workspace_members[] | match("(?<=path\\+file:)[^)]+") | .string'
    ///workspace/module1
    ///workspace/nested/module2
    ///workspace/nested/module3
    

    bash 循环中迭代它们:

    while read -r path; do
        # Something with $path
    done < <(cargo metadata | jq -r '.workspace_members[] | match("(?<=path\\+file:)[^)]+") | .string')
    

    或将行保存在数组中

    readarray -t paths < <(cargo metadata | jq -r '.workspace_members[] | match("(?<=path\\+file:)[^)]+") | .string')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多