当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在文件中搜索字符串或在 PowerShell 中使用 Grep

作者:精品下载站 日期:2024-12-14 22:01:10 浏览:13 分类:玩电脑

在文件中搜索字符串或在 PowerShell 中使用 Grep


PowerShell Grep 等效的 cmdlet 是 Select-String,它使用正则表达式来搜索文件中的字符串。 Powershell 中的 Select-String cmdlet 的工作方式类似于 UNIX 中的 grep 和 PowerShell 中的 findstr。

Select-String 搜索输入字符串或文件中的文本或文本模式。它显示文件名、行号以及包含匹配项的行中的文本。

[玩转系统] 在文件中搜索字符串或在 PowerShell 中使用 Grep

在本文中,我们将讨论 PowerShell grep 等效的 Select-String,使用 Get-ChildItem 在文件中递归搜索字符串,在文本中搜索与模式匹配的字符串。

PowerShell 在文件中搜索字符串

PowerShell 中的 Get-ChildItem 根据搜索条件获取一个或多个子项。

在 PowerShell 中使用 Select-String cmdlet 和 Get-ChildItem 以递归方式搜索文件中的字符串。

Get-ChildItem -Path D:\PowerShell\ -Recurse | Select-String -Pattern 'PSIsContainer' 

在上面的 PowerShell 脚本中,Get-ChildItem 使用参数 -Recurse 获取指定路径的一个或多个子项,并将输出通过管道传输到 Select-String 命令。

Select-String 使用Pattern 参数指定一个字符串来在文件中查找字符串。

在文件中成功匹配字符串后,Select-String 返回文件名、行号以及包含搜索文本的行。

用于在文件中查找字符串的 grep 等效 Select-String 命令的输出为:

[玩转系统] 在文件中搜索字符串或在 PowerShell 中使用 Grep

PowerShell 在文件中查找字符串

在 PowerShell 中使用 Select-String 在文件中查找字符串。它使用正则表达式匹配来搜索文件中的模式。

 Select-String -Path D:\PowerShell\*.* -Pattern 'Get-'  

在上面的 PowerShell 脚本中,Select-String 使用模式“Get-”在 Path 参数指定的文件中搜索字符串。

grep 文本文件的脚本的输出是:

PS C:\> Select-String -Path D:\PowerShell\*.* -Pattern 'Get-'   
                                    
D:\PowerShell\GetFileProperties-Assignment.txt:1:Get-ChildItem -File | Select name,CreationTime
D:\PowerShell\print-spooler-service-Test.ps1:1:$PrintSpooler = Get-Service -Name Spooler
D:\PowerShell\print-spooler-service.ps1:1:$PrintSpooler = Get-Service -Name Spooler

Select-String 在控制台上显示输出。它在文件中查找字符串并打印其文件名、行号和包含文本的行。

使用 Get-Content 在文件中搜索字符串

Get-Content 获取路径参数指定的文件的内容。它读取文件的内容并返回字符串对象。

使用以下命令使用 Get-Content 在文件中搜索字符串。

Get-Content -Path C:\Windows\my.ini
Get-Content -Path C:\Windows\my.ini | Select-String -Pattern "basedir*"     

在上面的 PowerShell 脚本中,

Get-Content 读取由 Path 参数指定的文件 my.ini 的内容。

它将字符串对象的内容通过管道传递给 Select-String 命令。它使用 Pattern 参数来查找字符串对象中的字符串。

上述在字符串对象中搜索字符串的脚本的输出是:

[玩转系统] 在文件中搜索字符串或在 PowerShell 中使用 Grep

在哈希变量中搜索字符串

使用PowerShell中的Select-String,您可以在哈希变量中搜索字符串。

让我们考虑一个示例,其中 hash 包含以下键值数据对并存储在 $mysqlInfo 变量中。

$mysqlInfo = @{
basedir='C:/Program Files/mysql'

datadir='C:/Program Files/mysql/data'

port='3306'

}

使用 Select-String 指定在变量中查找字符串的模式。

$mysqlInfo |Out-String -Stream | Select-String -Pattern 'datadir'

在上面的 PowerShell 脚本中,$mysqlInfo 变量输入通过管道传输到 Out-String -Stream。它将字符串对象格式化为多个单行字符串对象。

Select-String 使用 Pattern 参数指定要在变量中搜索的输入字符串并返回输出,如下所示:

$mysqlInfo |Out-String -Stream | Select-String -Pattern 'datadir'

datadir          C:/Program Files/mysql/data   

结论

我希望上面的文章使用 Select-String 在文件和变量中搜索字符串对您有所帮助。

使用 Select-String 在文件或变量中查找字符串,类似于 UNIX 中的 grep 命令和 Windows 中的 findstr 命令。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯