powershell - 使用 Powershell 从文本文件中选择特定字符串
问题描述
嗨,我有一个包含以下内容的文件
TAGS Name ASGonline-sys-system1-asg
TAGS aws:autoscaling:groupName ASGonline-sys-system1-asg20210107040213164400000001
我想从中获取一个特定的关键字ASGonline-sys-system1-asg。但是每当我尝试在命令下运行时,它都会给出错误的输出:
PS C:\Windows\system32> Select-String -Path C:\temp\instancename.txt -pattern 'ASGonline-sys-system1-asg'
> C:\temp\instancename.txt:26:TAGS Name ASGonline-sys-system1-asg
> C:\temp\instancename.txt:31:TAGS aws:autoscaling:groupName ASGonline-sys-system1-asg20210107040213164400000001
我也尝试了另一个命令 Get-Content 但似乎只有我得到的输出相同:
PS C:\Windows\system32> Get-Content C:\temp\instancename.txt | Where-Object { $_.Contains("ASGonline-sys-system1-asg") }
TAGS Name ASGonline-sys-system1-asg
TAGS aws:autoscaling:groupName ASGonline-sys-system1-asg20210107040213164400000001
我知道这是一个愚蠢的问题,但无论如何我只会得到输出ASGonline-sys-system1-asg
无论文件中的名称是什么,它只需要给我那个输出
解决方案
!?
param(
$exampleFileName = "d:\tmp\file.txt",
$pattern = "ASGonline-sys-system1-asg"
)
$PSVersionTable.PSVersion
@"
TAGS Name ASGonline-sys-system1-asg
TAGS aws:autoscaling:groupName ASGonline-sys-system1-asg20210107040213164400000001
"@ | Out-File $exampleFileName
$fileContent = Get-Content $exampleFileName -Raw
([regex]::Matches($fileContent, $pattern))[0].Value
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 1 0
ASGonline-sys-system1-asg
请原谅我的英语,据我了解,您想从文件内容中获取子字符串“ASGonline-sys-system1-asg”。这可以通过将文件的内容读入变量并对其应用正则表达式来完成。
推荐阅读
- flutter - Flutter URL 策略在 Web Release 上不起作用
- python - 如何在 Python 中的 Django 日历上创建“删除事件”按钮
- javascript - AngularFirestore 权限缺失或不足(Firebase 自定义令牌身份验证)
- python - 编写一个程序,在平面上输入三个点,它必须决定它们是否创建一个三角形,以及它们是否创建哪种类型
- ghostscript - 在 ubuntu 上运行 makefile 安装 ghostscript 时出错
- sql - 正则表达式仅用双引号替换第一个分号
- python - 从深度数组中提取列表
- c++ - C++ 随机数 -infinity 到 +infinity
- java - JTable 单元格中的 JButtons 在行选择时改变形状
- node.js - 查找数据时无法读取未定义的属性“查找”