
February 7th, 2013, 03:10 PM
|
 |
Contributing User
|
|
Join Date: Nov 2012
Location: Iran / France
|
|
I may have a solution but I don't claim that would be the best way of doing this.
One possible solution for me would be the following, assuming that the syntax of the file remains the same in the future (like automatic log files generated by a program)
Code:
import re
import sys
def main():
with open("testdata2.txt", "r") as inputFile:
# This is the aSN code provided as the command line argument
asnInputValue = sys.argv[1]
# Each line including the user name starts with "user" followed
# by something (that is, the actual user name), therefore the
# following regular expression pattern may be used in order to
# detect such line
userNameProg = re.compile(r"\"user\"[ ]+\"(?P<userName>[^ \"]+)\"")
# The regular expression matching the aSN code
asnProg = re.compile(r"\"aSN\"[ ]*=[ ]*\"(?P<asnValue>[^ \"]+)\"")
# start reading the file, line by line and looking for the
# corresponding matched regular expressions for user name and aSN.
userName = None
asnCode = None
for line in inputFile:
# user name found in the current line being processed
userNameMatched = userNameProg.match(line)
# aSN code found in the current line being processed
asnMatched = asnProg.match(line)
if userNameMatched:
userName = userNameMatched.group("userName")
elif asnMatched:
asnCode = asnMatched.group("asnValue")
if asnCode == asnInputValue:
print ("The user name for the aSN code {0} is {1}".
format(asnCode, userName))
else:
continue
main()
I run this script (I use Python 3) with the following test file
Code:
"user" "test1"
{
"name" = "test1"
"princName" = "test1@local"
"cn" = "test1"
"ID" = 12345
"aSN" = "TRI1"
}
"user" "test2"
{
"cn" = "test2"
"sAmname" = "test2"
"email" = "test2@corp.com"
"ID" = 422223
"aSN" = "TRI2"
}
"user" "test3"
{
"cn" = "test2"
"sAmname" = "test2"
"email" = "test2@corp.com"
"ID" = 422223
"aSN" = "TRI3"
}
"user" "test4"
{
"cn" = "test4"
"sAmname" = "test4"
"email" = "test4@corp.com"
"ID" = 422223
"aSN" = "TRI4"
}
And here is the result that I obtain:
Code:
$ python -tt myscript.py TRI1
The user name for the aSN code TRI1 is test1
$ python -tt myscript.py TRI2
The user name for the aSN code TRI2 is test2
$ python -tt myscript.py TRI3
The user name for the aSN code TRI3 is test3
$ python -tt myscript.py TRI4
The user name for the aSN code TRI4 is test4
Regards,
Dariyoosh
|