Home > OS >  Bash: Extract variable value from string
Bash: Extract variable value from string

Time:11-30

I'd need to extract the value of a variable "error" from a log file. Here's a sample line:

WARN (Periodic Recovery) IJ000906: error=15 check server.log

I'd need to capture the value of "error". Looking on similar answers, I've come up with:

echo "WARN (Periodic Recovery) IJ000906: error=15 check server.log" |  grep -P '\d  (error=?)' -o

However it does not produce any value. Can you recommend a working solution for this case?

CodePudding user response:

Using sed

$ echo "WARN (Periodic Recovery) IJ000906: error=15 check server.log" | sed 's/.*error=\([^ ]*\).*/\1/'
15

CodePudding user response:

For a perl-compatible regular expression, you're looking for a "lookbehind" assertion.

To find digits that are preceded by the string "error=", you want:

echo "$line" | grep -o -P '(?<=error=)\d '    # => 15

See the pcresyntax(3) man page

CodePudding user response:

You may use this grep:

s='WARN (Periodic Recovery) IJ000906: error=15 check server.log'
grep -oP '\d : error=\K\d ' <<< "$s"

15

RegEx Details:

  • \d :: Match 1 digits followed by colon and space
  • error=: Match error= text
  • \K: Reset matched info
  • \d : Match 1 digits and print it

CodePudding user response:

I would use GNU AWK following way, let file.txt content be

WARN (Periodic Recovery) IJ000906: error=15 check server.log

then

awk 'BEGIN{FPAT="error=[0-9] "}{print substr($1,7)}' file.txt

output

15

Explanation: I inform GNU AWK that column is error= followed by 1 or more digits using field pattern (FPAT), for every line print first field starting from 7th charater, using substr string function. 7 as error= has 6 characters. Note: this solution will print first occurence of error=value for each line.

(tested in gawk 4.2.1)

CodePudding user response:

With bash >= 3.0.

v='WARN (Periodic Recovery) IJ000906: error=15 check server.log'

[[ $v =~ error=([0-9] ) ]] && echo "${BASH_REMATCH[1]}"

Output:

15
  • Related