Issue
I have a variable which has content like
----- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- All files | 36.95 | 20.87 | 24.
PS: The output I mentioned is actually pretty long and I trimmed it for the sake of posting here. I found out by trial and error that All files <> | was between position 970-990
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 975-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.
Solution
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)"
Here's a tiny script with that idea put to use:
#!/bin/bash
RES="----- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- All files | 36.95 | 20.87 | 24."
TOTAL="$(sed -E 's/^.* All files \| ([^ ]+) \| .*$/\1/' <<< $RES)"
echo "$TOTAL"
Running that:
$ ./test.sh
36.95
Answered By - Erwin Answer Checked By - Marie Seifert (WPSolving Admin)