How to modify this script to search for multiple keywords?

Viewed 56

I am trying to modify a script. It is being difficult for me so I came for help. This script is supposed to extract data from some .out files and then write them in a .txtfile. The problem is that I have two different keywords to look for. So, I provide the script, the things I am not able to modify and then two examples of input files.

#!/usr/bin/env python
# -*- coding: utf-8

#~ Data analysis
import glob, subprocess, shutil, os, math
from funciones import *
for namefile in glob.glob("*.mol2"):
    lstmol2 = []
    lstG=[]
    os.chdir("some_directory")
    searchprocess="grep -i -H 'CURRENT VALUE OF HEAT OF FORMATION =' *.out | sort -k 4 > firstfile.txt" 
#~I need also to look for 'CURRENT BEST VALUE OF HEAT OF FORMATION ='
    os.system(searchprocess)

    fileout=open("results.txt","w")   
    filein=open("firstfile.txt", "r")
    #~ write data in results.txt
    fileout.write('\t %s \n' %("  HOF"))

    for line in filein:
        linediv=line.split()
        HOF=float(linediv[8])

  #~or [10] (for the keyword in need to add) but in both cases I need the float. I need both data of the keywords be included on this file.
        lstG.append(HOF)  
     fileout.close()  
    filein.close()

Input data, type 1:

foofoofooofoofoofoofoofoo
foofoofooofoofoofoofoofoov
foofoofooofoofoofoofoofoo
CURRENT VALUE OF HEAT OF FORMATION = 1928
foofoofooofoofoofoofoofoo
foofoofooofoofoofoofoofoov

Input data, type 2:

foofoofooofoofoofoofoofoo
foofoofooofoofoofoofoofoov
foofoofooofoofoofoofoofoo
CURRENT BEST VALUE OF HEAT OF FORMATION = 1930
foofoofooofoofoofoofoofoo
foofoofooofoofoofoofoofoov
1 Answers

You should update your grep command to look for the optional word with the ? operator. Use the -E flag to enable exteneded regular expressions so you don't have to escape your regex operators. Always use single quotes around your pattern:

searchprocess="grep -E -i -H 'CURRENT( BEST)? VALUE OF HEAT OF FORMATION =' *.out | sort -k 4 > firstfile.txt"

@PrestonHager is correct that you should change linediv[8] to linediv[-1], since in the cases where BEST is present, the number will be in the linediv[9] position, but in both cases linediv[-1] will give you the desired result.

Related