0

I am trying the following in a bash script on Linux:

envA="prdk8s--staging-a"
envB="prd-k8s--sandbox"

for envCode in $envA $envB;
do
   Code=$(echo $envCode | cut -d "--" -f 1)
   echo $Code
done

However, this fails:

cut: the delimiter must be a single character
Try 'cut --help' for more information.

Expected output:

staging
sandbox

Is there a way to print the next word after "--" in the variable values $envA and $envB?

1
  • could you also please comment about the downvote so that it helps me in future? thx!
    – james
    May 18, 2021 at 13:18

1 Answer 1

1

You can use the shell's own parameter expansions to trim the leading and trailing components:

for envCode in "$envA" "$envB"; do 
  t=${envCode#*--}
  printf '%s\n' "${t%-*}"
done
staging
sandbox

You can use ##, %% if you want to remove the longest rather than the shortest leading and trailing matches - it's not clear from your examples which is required.

See for example BashGuide: Parameter Expansion

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .