Denys
Denys

Reputation: 4557

Parse a name out of a string

There are many server logs that need to be analyzed. Every log message is a string and I'm looping though those stings.

Problem:

I need to see if the string matches the pattern

some text Job *some_one_word_name* has finished, status some more text

I need to save the word between words Job and has finished. In this particular case (see below) I would save the EgiMmsWellHdr

 Seq_Loading_SOR_to_Landing..JobControl (DSWaitForJob): Job EgiMmsWellHdr has finished, status = 1 (Finished OK)

Upvotes: 1

Views: 59

Answers (4)

BMW
BMW

Reputation: 45293

Using gnu grep

grep -oP ": Job \K.*(?=has finished)" log.file

EgiMmsWellHdr

or

grep -oP "(?<=: Job ).*(?=has finished)" file

Seems you don't support -P and -o option, try this sed command

sed -n 's/.*: Job \(.*\) has finished.*/\1/p' file

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74685

Using bash regular expressions:

re="Job (\w+) has finished" 
while read line
do 
    [[ "$line" =~ $re ]] && echo "${BASH_REMATCH[1]}"
done <<<"Seq_Loading_SOR_to_Landing..JobControl (DSWaitForJob): Job EgiMmsWellHdr has finished, status = 1 (Finished OK)"

output:

EgiMmsWellHdr

The \w is shorthand for the characters a-z and A-Z. Instead of the <<< which I used, you could indirect a file using < filename.

Upvotes: 0

Nachiket Kate
Nachiket Kate

Reputation: 8571

Try this,

[root@server1]# str="Seq_Loading_SOR_to_Landing..JobControl (DSWaitForJob): Job EgiMmsWellHdr has finished, status = 1 (Finished OK)"
[root@server1]# echo $str | cut -d ":" -f2 | cut -f3 -d " "
EgiMmsWellHdr

Upvotes: 0

anubhava
anubhava

Reputation: 785481

You can use awk:

s='Job EgiMmsWellHdr has finished'
awk -F 'Job | has finished' '{print $2}' <<< "$s"
EgiMmsWellHdr

And using pure BASH:

[[ "$s" =~ "Job "([^[:blank:]]+)" has finished" ]] && echo ${BASH_REMATCH[1]}
EgiMmsWellHdr

Upvotes: 2

Related Questions