简体   繁体   English

Powershell 选择字符串

[英]Powershell Select-String

I need your help with PowerShell.我需要你的 PowerShell 帮助。

I need Select-String with fixed Date (in variable).我需要带有固定日期(可变)的 Select-String。 & Set-Content to result.txt Example: $Date = "01.07.2020" & 将内容设置为 result.txt 示例: $Date = "01.07.2020"

But also i need select string with date which lower than i written in variable.但我也需要选择日期低于我写在变量中的字符串。

My code: Get-Content -Path log.txt | Select-String "?????" | Set-Content $result.txt我的代码: Get-Content -Path log.txt | Select-String "?????" | Set-Content $result.txt Get-Content -Path log.txt | Select-String "?????" | Set-Content $result.txt

  • In log.txt i have many strings like " Creation date 01.07.2020 " ;在 log.txt 中,我有很多字符串,例如“创建日期 01.07.2020”; " Creation date 01.06.2020 " " 创建日期 01.06.2020 "

123.txt 123.txt

Creation date 01.07.2020
Creation date 02.05.2020
Creation date 01.06.2020
Creation date 28.08.2020

Example script示例脚本

$file = "C:\Users\userprofile\Desktop\test\123.txt"
$regexpattern = "\d{2}\.\d{2}\.\d{4}"
$content = Get-Content $file | Where-object { $_ -match $regexpattern}

foreach($line in $content){

    $line.Substring(13,11)

}

I used regex to find the lines you are wanting to output.我使用正则表达式来查找您想要输出的行。 We get the content only if it matches our regex, then for each line we found, I'm using substring to pull the date out.只有当内容与我们的正则表达式匹配时,我们才能获取内容,然后对于我们找到的每一行,我使用子字符串来提取日期。 You could also put together a regex for this if you wanted to.如果您愿意,您也可以为此组合一个正则表达式。 Since we know the lines have the same number of characters it's safe to use the substring function.由于我们知道这些行具有相同数量的字符,因此使用 substring 函数是安全的。

If you want that output to a file, simply find $line.Substring(13,11) and then add this after it | Out-file "C:\\Users\\userprofile\\desktop\\test\\output.txt" -append如果你想要输出到一个文件,只需找到$line.Substring(13,11)然后在它后面添加这个| Out-file "C:\\Users\\userprofile\\desktop\\test\\output.txt" -append | Out-file "C:\\Users\\userprofile\\desktop\\test\\output.txt" -append . | Out-file "C:\\Users\\userprofile\\desktop\\test\\output.txt" -append

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM