Reputation: 2972
I have a big file with some lines like:
And another file with:
I want to make just one file, replacing the first field of Data.txt with the second field in Users.txt. On the final, it may look like this:
I have made the following code in python.
with open("File", "r") as sources:
lines = sources.readlines()
with open("File", "w") as sources:
for line in lines:
sources.write(re.sub(r'TextToReplace', 'ParameterToReplace', line))
I need to replace TextToReplace with the first field on the file Users.txt and the ParameterToReplace is the second field on Users.txt. Many times, with 30M+ parameters.
It's like a command sed 's/TextToReplace/ParameterToReplace/" File
Upvotes: 0
Views: 10040
Reputation: 1298
you can use dict if data has mixed:
userdict={}
for i in open("users.txt","r").read().split("\n"):
arr=i.split(":")
userdict[arr[0]]=arr[1]
with open("final.txt","w") as f:
for i in open("data.txt","r").read().split("\n"):
arr=i.split(":")
f.write("{}:{}".format(userdict[arr[0]],arr[1]))
Upvotes: 1
Reputation: 247220
The join
command is useful for this kind of thing.
Assuming your shell understands Process Substitutions:
$ join -o 1.2,2.2 -t: <(sort users.txt) <(sort data.txt)
jhonny:Brown
Mary:Green
Jane:Yellow
Upvotes: 0