如何选择字符串并仅输出最后一个文本行

时间:2019-05-13 00:47:41

标签: powershell

无论如何,我只能让输出搜索我搜索的每个字符串的最后一行吗?

$String1 = "Oatmeal"
$String2 = "Cake"
$String1Location = "C:\1.txt"

try {
    Select-String -Path $String1Location -Pattern $String1, $String2 -ErrorAction Stop 
}

catch {
    return ""
}

我的输出是这样的:

C:\1.txt:4:Oatmeal
C:\1.txt:6:Cake
C:\1.txt:9:Cake
C:\1.txt:10:Oatmeal

但是我只想看看

C:\1.txt:9:Cake
C:\1.txt:10:Oatmeal

谢谢。

4 个答案:

答案 0 :(得分:0)

如果在try块中执行以下操作,该怎么办?

$found1=Select-String -Path $String1Location -Pattern $String1 -ErrorAction Stop 
$found1[-1]
$found2=Select-String -Path $String1Location -Pattern $String2 -ErrorAction Stop 
$found2[-1]

答案 1 :(得分:0)

这是我最终得到的,并且可以正常工作:

y=1

答案 2 :(得分:0)

我建议这样做:

$String1 = "Oatmeal"
$String2 = "Cake"
$String1Location = "C:\1.txt"

Select-String -Path $String1Location -Pattern $string1, $string2 -SimpleMatch | Group-Object Line | ForEach-Object {
    $_.Group | Sort-Object LineNumber | Select-Object -Last 1
}

或使用正则表达式匹配

$StringsToSearch = "Oatmeal","Cake"
$String1Location = "C:\1.txt"

# build the regex
$pattern = '\b(' + (($StringsToSearch | ForEach-Object { [regex]::Escape($_) }) -join '|') + ')\b' 
# this ends up in '\b(Oatmeal|Cake)\b' which means we are looking for these strings as whole string.
# if you also would like to search for strings that contain the search criteria, like 'Pancake',
# then use 
# $pattern = ($StringsToSearch | ForEach-Object { [regex]::Escape($_) }) -join '|'

Select-String -Path $String1Location -Pattern $pattern | Group-Object Line | ForEach-Object {
    $_.Group | Sort-Object LineNumber | Select-Object -Last 1
}

注意:如果要在行号上按升序对输出进行排序,只需在最后一个大括号后添加| Sort-Object LineNumber

答案 3 :(得分:0)

最简单的解决方案是IMO附加SFTPAttributes
以及st_mtime拥有原始订单所必需的。

st_mtime