I have a variable which has content like
----- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- All files | 36.95 | 20.87 | 24.
I am trying to extract the value associated with All files i.e 36.95. I am able to use cut to get the substring like this
TOTAL="$(cut -c 60-990 <<< $RES)"
But I am looking for better approach for example using a regex pattern, I saw patterns like grep and awk but I am not able to formulate it.
CodePudding user response:
cut
can define fields based on a delimter so this should work (assuming the number you're looking for will always be in the 12th |
-delimited field):
$ TOTAL=$(cut -d'|' -f12 <<< "${RES}")
$ typeset -p TOTAL
declare -- TOTAL=" 36.95 "
$ TOTAL="${TOTAL// /}" # to remove spaces
$ typeset -p TOTAL
declare -- TOTAL="36.95"
CodePudding user response:
If you're not limiting yourself to cut
, this is a possible answer using sed
that looks for the All files | ... |
pattern and grabs the text from there.
TOTAL="$(sed -E 's/^.* All files \| ([^ ] ) \| .*$/\1/' <<< $RES)"
CodePudding user response:
And since you mentioned it - here an awk
alternative:
total=$(awk -F'|' '{print $12}'<<<"${res}")
Note: all uppercase variable names are (more by convention than anything) reserved for the system.