【问题标题】:How to find a specific text in a txt file using Powershell如何使用 Powershell 在 txt 文件中查找特定文本
【发布时间】:2021-02-08 22:09:11
【问题描述】:

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

喜欢:

User1 
User2 
User3

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

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

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

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

文件没有标题。


更新

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

u16096

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

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

【问题讨论】:

  • powershell.exe 中,我将使用内置的findstr.exe 实用程序,与在cmd.exe 中的方式完全相同findstr.exe /IG:"L:\ocation\first.txt" "P:\athTo\second.txt"跨度>
  • 也感谢您的评论,我试过了,但它不适用于我的两个文件
  • 它在cmd.exepowershell.exe 中都可以完美地使用您提供的内容。没有看到您的实际文件,我无法确定具体原因。使用现有答案下的评论示例,它看起来更像findstr.exe /IG:"C:\temp\test2\results5.csv" "C:\temp\test2\userstotal.txt"。这将获取C:\temp\test2\results5.csv 的每一行,这应该是一个用户列表,每行一个,如您的第一个文本文件示例中一样,并输出与这些字符串部分匹配的C:\temp\test2\userstotal.txt 的每一行。

标签: powershell txt


【解决方案1】:

我就是这样做的。 cmets 中的解释。我无法准确地测试它,我没有你的原始文件,但它应该能让你开始。

# 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"

【讨论】:

  • 感谢您的快速回复,但我一定是做错了什么,因为第三个文件是空的。请给我举个例子。
  • 这就是我所说的。 # 将第二个文本文件的值存储在查找映射中 $userInfos = @{} Get-Content "C:\temp\test2\userstotal.txt" | foreach { # 使用用户名作为查找键 $username = $_ -replace '^(\S+).*', '$1' $userInfos[$username] = $_ } # 迭代第一个文件,查找用户信息,并输出到第三个文件 Get-Content "C:\temp\test2\results5.csv" | foreach { $userInfos[$_.Trim()] } |输出文件“C:\temp\test2\usertotal_result.txt”
  • ,好的,我拿出了文件。什么都没有出来,我用同样的例子。在这部分,$userInfos = @{what do you put here}?
  • 好的,它工作正常。我发现出了什么问题。它适用于我的示例,但不适用于原始文件 :( 显然原始文件包含私人数据,我无法显示在这里。请问,如果 txt 2 文件的大小大于 2 MB,它可能会失败?或者它可能会失败,因为原始文件中的 - 而不是空格。我会更新我的问题,以便您看到。
  • 好的,所以它的大小,使用较少的用户它工作得很好。我可以使用 2mb 的 txt 文件吗?
猜你喜欢
  • 2011-12-23
  • 1970-01-01
  • 2011-03-26
  • 2016-06-29
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多