Question

This is my Log text:

03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt 

From the above Log text i want to get the middle string i.e:

Virus infected content detected while scanning file

How do i get only this string ?

I have written the below code:

result=`tail  /home/eng/Shellscripts/result.txt | grep "PFM_DIP_SERVER_001:" | cut -f1 -d";"  `
echo "$result"

Output:

03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file
Was it helpful?

Solution

You can try this,

tail result.txt | grep -o "PFM_DIP_SERVER_001:[^;]*" | cut -d: -f2

OTHER TIPS

I would go for a awk version with multiple delimiters:

awk -F"[:;]" '{print $4}'

It looks for the 4th field based on two possible delimiters: ; or :.

This awk version would allow you to also bypass the grep step:

result=$(tail /home/eng/Shellscripts/result.txt | awk -F"[:;]" '/PFM_DIP_SERVER_001:/ {print $4}')

In case you want to use cut, take the : delimiter and get the 4th element, and then the 1st based on the ; delimiter:

cut -d':' -f4 file | cut -d';' -f1

All together:

result=$(tail /home/eng/Shellscripts/result.txt | grep "PFM_DIP_SERVER_001:" | cut -d: -f4 | cut -d';' -f1)

If we assume that the given search string will be identical on all occurrences you could use bash parameter expansion.

In the following examples I assume that a variable named result will contain the string 03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt.

One possibility would be to use substring expansion:

$ result="03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt"

$ result="${result:51:51}"
$ echo "$result"
Virus infected content detected while scanning file

The first value represents an offset starting from the beginning of the string, the second value describes the length starting at the end of the offset.

A second possibility could be to use substring removal:

$ result="03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt"

# Remove everything from the beginning of the string
# until the first occurence of "001:"
$ result="${result#*001:}"
$ echo "$result"
Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt

# Remove everything from the end of the string
# until the first occurence of ";"
$ result="${result%;*}"
$ echo "$result"
Virus infected content detected while scanning file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top