我在文本文件中查找包含特定字符的字符串;我使用
Select-String -Path clm-server-test.txt -Pattern "#(S****)"我只想获取与模式匹配的字符,但它还返回该字符串之前和之后的字符。
例如:
我有一个注册集,它以
S32145 thomas
S12345 bedro
S09867 stephane使用Select-String命令,我希望它显示所有的S ***单词,而不是名称。
发布于 2018-09-06 00:54:42
默认情况下,
Select-String's -Pattern参数需要 (regular expression)来搜索。- `"#(S****)"` is _not a valid regex_ (it looks more like a _wildcard expression_, except that you'd use `?` to match a single character).
- To match just the tokens that start with `S` followed by 5 digits, use `S\d{5}`, or, to match any number of digits, use `S\d+`, as [TheIncorrigible1](https://stackoverflow.com/users/8188846/theincorrigible1) suggests.还可以将正则表达式优化为仅在单词边界(\b)处匹配:'\bS\d{5}\b'
Select-String不支持仅输出行的匹配部分,但可以通过进一步处理它输出的[Microsoft.PowerShell.Commands.MatchInfo]实例来实现。将所有这些放在一起:
Select-String -Path clm-server-test.txt -Pattern '\bS\d{5}\b' |
ForEach-Object { $_.Matches[0].Value }对于您的示例输入,这将产生以下结果:
S32145
S12345
S09867 顺便说一句:从上面的命令可以明显看出,Select-String目前并不能轻松地仅提取输入行的匹配部分。
如果您有兴趣引入一个开关来简化这一点,请访问participate in the discussion on GitHub。
发布于 2018-09-07 00:19:30
谢谢你的回答,事实上,你的命令让我更接近预期的结果,除了这一点,我希望他给我返回以"S *“开头的单词,直到现在,在所有我想要避免的事情上。
我想让他给我看"S7676583“这个号码
非常感谢
https://stackoverflow.com/questions/52189780
复制相似问题