sharpmartin6 sharpmartin6 - 7 months ago 12
Bash Question

Extract two substrings from line in bash then concatenate them

This solution will be part of a script.

Given an error log, I need to extract the failed status/reason for failure and the username, then concatenate them so the output can be sent in an email.

My output should look something like this:

Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,username=FOO
Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,username=BAR


Each line in the error log file closely resembles this:

"{ Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO},...sendAcctActNotif=N}}"


There are no ellipses in the file; each line contains considerably more than is shown, but I have shown only the important parts.

Answer

Using this answer you can extract some part of your line (if it always looks the same way)

s="{ Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO}, {username=BAR}...sendAcctActNotif=N}}"

status=`grep -oP '(?<=Operation status:).*?(?=Sent)' <<< "$s"`
user=`grep -oP '(?<=username=).*?(?=})' <<< "$s"`
echo "Operation status:" $status "username="$user

output :

Operation status: failed,Job Description not updated because this is not a matching Job Description ID., username=FOO

EDIT : if you want to keep only the first instance of the username you can add "head -n 1" :

user=`grep -oP '(?<=username=).*?(?=})' <<< "$s" | head -n 1`
Comments