Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Compare two text files in Powershell and if a name is found in both files output content from file 2 to a 3rd text file

$
0
0

Is it possible using PowerShell to compare the contents of two text files line by line and if a line is found output that line to a third text file?

Lets say hypothetically someone asks us to search a text file named names1.txt and when a name is found in names1.txt we then pair that with the same name in the second text file called names2.txt

lets say the names shown below are in names1.txt

Bob

Mike

George

Lets say the names and contents shown below are in names2.txt

Lisa

Jordan

Mike 1112222

Bob 8675309

Don

Joe

Lets say we want names3.txt to contain the data shown below

Mike 1112222

Bob 8675309

In vbscript I used search and replace commands to get part of the way there like this

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("testing.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Mike ", "Mike 1112222")

Set objFile = objFSO.OpenTextFile("testing.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

That script works great when you know the name you are looking for and the correct values. Lets say someone gives you a list of 1000 employees and says import these names into a list in the correct format and one sheet has the correct names only and the other sheet has lots of extra names say 200000 and you only need the 1000 you are looking for in the format from names2.txt.









Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>