3

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

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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 (...)

Comments

1

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 ')'

Comments

1

Another way using grep and tr:

echo "NAME(APACHE) STATUS(Not Running)" | grep -o '([^)]\+)$' | tr -d '()'

The regex ([^)]\+)$ matches anything in between parenthesis at the end of the line.

The tr command is deleting the parenthesis.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.