Home > OS >  Split, find and iterate over output of command
Split, find and iterate over output of command

Time:10-03

I currently have the following bash command:

cargo metadata | jq .workspace_members[]

And it returns something like the following:

"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)"

I would like to split the string/stream/input by new lines and find (using the regexp path\ file\:(.*)\)) the file path on each line. And then be able to iterate over them:

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

Which would then print out the paths:

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

CodePudding user response:

You can extract the paths using just jq, with its regular expression based match filter:

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

To iterate over them in a bash loop:

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

or save the lines in an array

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