首页 > 解决方案 > 如何使用 Powershell 在 txt 文件中查找特定文本

问题描述

我有一个.txt文件,列出了一些用户名。

喜欢:

User1 
User2 
User3

我还有一个.txt文件,其中包含一些相同的用户名以及其他信息:

User1 - user1@txt.com - 12341515 - yes
User2 - user2@txt.com - 13134141 - no

如何从第一个文件中搜索第二个文件中的用户,然后在新的 txt 文件中输出第二个文件的完整行。

我试过 , Get-contentand |where-object,但我不知道如何准确搜索。

这些文件没有标题。


更新

file1,我要查找的用户在哪里是这样的

u16096

原始文件2,所有用户信息都具有此顺序。

u16096      Y   NAME SURNAME    name.surname@what.com           12345678

标签: powershelltxt

解决方案


我就是这样做的。评论中的解释。我不能完全测试它,我没有你的原始文件,但它应该让你开始。

# store the values of the 2nd text file in a lookup-map
$userInfos = @{}
Get-Content "file2.txt" | foreach {
    # use the username as lookup key
    $username = $_ -replace '^(\S+).*', '$1'
    $userInfos[$username] = $_
}

# iterate the 1st file, lookup the user infos, and output to 3rd file
Get-Content "file1.txt" | foreach {
    $userInfos[$_]
} | Out-File "file3.txt"

推荐阅读