Sankar
Sankar

Reputation: 323

How to cut the string using bash command

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

Upvotes: 3

Views: 6363

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 2

Inian
Inian

Reputation: 85560

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

Upvotes: 4

oliv
oliv

Reputation: 13249

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.

Upvotes: 1

Zumo de Vidrio
Zumo de Vidrio

Reputation: 2091

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

Upvotes: 1

Related Questions