7

What would be the command to remove everything after a string (\test.something). I have information in a text file, but after the string there is like a 1000 lines of text that I don't want. how can I remove everything after and including the string.

This is what I have - not working. Thank you so much.

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

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

2 Answers 2

6

Why remove everything after? Just keep everything up to it (I'm going to use two lines for readability but you can easily combine into single command):

$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

Also, you may not need the Trim but you were using TrimEnd so added in case you want to add it later. )

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thank you so much.... works real good. without you guys I might as well go home and cry in the corner.
6

Using -replace

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

5 Comments

removes the string and everything after on that line only. Doesn't delete the rest of the 999 lines. thanks for helping me.
Did you add that -Raw switch to Get-Content?
sure did ------ $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 "file.txt"')) | Set-Content "file.txt"
You need to turn on the singleline flag (?s) so the regex matches newlines and it's harder to write those with powershell would look something like: $text -replace "(?s)\\test\.something\\.*\r\n.*","" or using `n for newline
@JGreenwell Good catch!. In this instance the newlines don't matter. They'll all get included in the trailing ',+'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.