How to cut the following string and retrieve "Not Running" Status in Bash.
I have tried cut command cut -d"STATUS", It is throwing exception
EX:
$ echo "NAME(APACHE) STATUS(Not Running)
Expected String:
Not Running
Using the bash, regex operator ~
string="NAME(APACHE) STATUS(Not Running)"
[[ $string =~ ^.*STATUS\((.*)\)$ ]] && printf "%s\n" "${BASH_REMATCH[1]}"
Not Running
Using Awk as () de-limiter,
echo "NAME(APACHE) STATUS(Not Running)" | awk 'BEGIN{FS="[()]"}{print $4}'
Not Running
Using a double-fold parameter substitution, as bash does not support nested parameter expansions,
temp1="${string#*)}"
temp2="${temp1%*)}"
printf "%s\n" "${temp2#*STATUS(}"
Not Running
Using GNU grep with its PCRE - Perl Compatible Regular Expressions capabilities, with the -P flag,
grep -oP '.*STATUS\(\K[^\)]+' <<<"$string"
Not Running
Alternative solutions:
using sed command:
echo "NAME(APACHE) STATUS(Not Running)" | sed -rn 's/.*\(([^)]+)\)$/\1/p'
using perl implementation:
echo "NAME(APACHE) STATUS(Not Running)" | perl -lne 'print $1 if /\(([^)]+)\)$/'
using awk command(treating braces )( as field separator FS):
echo "NAME(APACHE) STATUS(Not Running)" | awk 'BEGIN{FS="[)(]"}{ print $(NF-1) }'
$(NF-1) - points to the last non-empty field
\(([^)]+)\)$/ - regex pattern, will match a character sequence between braces at the end of the string
\1(within sed expression) and $1(within perl expression) point to the first captured group (...)
The command cut -d only works with single character delimiters, that's why you cannot use "STATUS" as delimiter.
You may use awk instead, or use cut with another delimiter, for example "(":
echo "NAME(APACHE) STATUS(Not Running)" | cut -d'(' -f3
Which will give the output:
Not Running)
Then you can remove the last ")" with tr:
echo "NAME(APACHE) STATUS(Not Running)" | cut -d'(' -f3 | tr -d ')'