How to extract string of command result and use it in a loop

Viewed 170

Running a nx affected:apps command gives me this output:

>  NX   NOTE  Affected criteria defaulted to --base=master --head=HEAD


>  NX  Affected apps:

  - app-backend
  - app-frontend
  - app-something
  - app-anything

I need to get all the application names and use them again for a command call.

So I started with that

output=$(nx affected:apps)  
echo "$output" | grep -E "^\W+app-(\w+)"

This gives me

- app-backend
- app-frontend
- app-something
- app-anything

But I need to get the names only instead to run foo --name={appname} four times. Also not quite sure how to use it in a loop. Quite new to bash scripting :-(

3 Answers

You may use -o (show matches only) with -P (perl regex moode) in gnu-grep:

nx affected:apps |
grep -oP "^\W+app-\K\w+" |
xargs -I {} docker build -t {} .

If gnu-grep isn't available then use this awk command:

nx affected:apps |
awk -F- '/app-/{print $3}' |
xargs -I {} docker build -t {} .

I don't have nx command here but you can try using xargs:

nx affected:apps | grep '^  -' | cut -d' ' -f4 | xargs  -I{}  echo docker build -t {} ./dist/{}

Remove echo to actually run the command.

You can use the --plain option:

nx affected:apps --plain

the command should return all the affected apps with space as a divider. You can then store those to a bash array and cycle through them in a for loop, running the command you need:

#!/bin/bash
AFFECTED=($(./node_modules/.bin/nx affected:apps --plain))

for t in ${AFFECTED[@]}; do
    echo $t
done
Related