【问题标题】:powershell trim - remove all characters after a stringpowershell tr​​im - 删除字符串后的所有字符
【发布时间】:2015-05-19 07:35:39
【问题描述】:

删除字符串 (\test.something) 之后的所有内容的命令是什么。 我在文本文件中有信息,但在字符串之后有 1000 行我不想要的文本。如何删除字符串之后的所有内容。

这就是我所拥有的 - 不工作。非常感谢。

$file = get-item "C:\Temp\test.txt"

(Get-Content $file) | ForEach {$_.TrimEnd("\test.something\")} | Set-Content $file

【问题讨论】:

    标签: powershell trim


    【解决方案1】:

    使用-replace

    (Get-Content $file -Raw) -replace '(?s)\\test\.something\\.+' | Set-Content $file
    

    【讨论】:

    • 仅删除该行之后的字符串和所有内容。不删除其余 999 行。谢谢你帮助我。
    • 您是否将 -Raw 开关添加到 Get-Content?
    • 确定 ------ $text = ( Get-Content "file.txt" -raw | Out-String ).Trim() $text.Substring(0,$text.IndexOf ('$text = ( Get-Content "file.txt" -raw | Out-String ).Trim() $text.Substring(0,$text.IndexOf('Folder: \Microsoft')) | Set-Content "文件.txt"')) |设置内容“file.txt”
    • 您需要打开单行标志 (?s),以便正则表达式匹配换行符,并且使用 powershell 编写的那些看起来像:$text -replace "(?s)\\test\.something\\.*\r\n.*","" 或使用 `n 换行
    • @JGreenwell 很好!在这种情况下,换行符无关紧要。它们都将包含在尾随的“,+”中。
    【解决方案2】:

    为什么之后要删除所有内容?保持一切顺利(我将使用两行代码以提高可读性,但您可以轻松组合成单个命令):

    $text = ( Get-Content test.txt | Out-String ).Trim() 
    #Note V3 can just use Get-Content test.txt -raw
    $text.Substring(0,$text.IndexOf('\test.something\')) | Set-Content file2.txt
    

    此外,您可能不需要 Trim,但您使用的是 TrimEnd,因此添加,以防您以后想添加它。 )

    【讨论】:

    • 太棒了,非常感谢您.... 真的很好用。没有你们,我还不如回家在角落里哭。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2018-05-31
    • 2012-10-19
    • 1970-01-01
    • 2014-11-08
    • 2011-04-28
    相关资源
    最近更新 更多