这是我的日志文字:
03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file; File name: 2MBVirusTextFile.txt
从上面的Log文本中我想获得中间字符串 即:
Virus infected content detected while scanning file
我如何只得到这个字符串?
我写了以下代码:
result=`tail /home/eng/Shellscripts/result.txt | grep "PFM_DIP_SERVER_001:" | cut -f1 -d";" `
echo "$result"
输出:
03/17/2014 13:48:40.016- null - PFM_DIP_SERVER_001:Virus infected content detected while scanning file
答案 0 :(得分:0)
我会选择带有多个分隔符的awk
版本:
awk -F"[:;]" '{print $4}'
它会根据两个可能的分隔符查找第4个字段:;
或:
。
此awk
版本允许您绕过grep
步骤:
result=$(tail /home/eng/Shellscripts/result.txt | awk -F"[:;]" '/PFM_DIP_SERVER_001:/ {print $4}')
如果您想使用cut
,请取:
分隔符并获取第4个元素,然后根据;
分隔符获取第1个元素:
cut -d':' -f4 file | cut -d';' -f1
所有在一起:
result=$(tail /home/eng/Shellscripts/result.txt | grep "PFM_DIP_SERVER_001:" | cut -d: -f4 | cut -d';' -f1)
答案 1 :(得分:0)
你可以试试这个,
tail result.txt | grep -o "PFM_DIP_SERVER_001:[^;]*" | cut -d: -f2
答案 2 :(得分:0)
如果我们假设给定的搜索字符串在所有出现时都相同,则可以使用bash parameter 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
。
一种可能性是使用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
第一个值表示从字符串开头开始的偏移量,第二个值表示从偏移量末尾开始的长度。
第二种可能是使用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