Michelle Santos
Michelle Santos

Reputation: 267

Remove 1st few characters from a text file using Powershell

I have a text file that contains the data similar below:

2020-05-04T00:00:16.120X "2020-05-04 08:00:02:562" "apple"
2020-05-04T01:00:16.140X "2020-05-04 09:00:02:488" "banana"
2020-05-04T02:00:48.160X "2020-05-04 10:00:02:509" "cherry"
2020-05-04T03:00:54.182X "2020-05-04 11:00:02:518" "papaya"

I want to remove the first column that contains the dateX:

"2020-05-04 08:00:02:562" "apple"
"2020-05-04 09:00:02:488" "banana"
"2020-05-04 10:00:02:509" "cherry"
"2020-05-04 11:00:02:518" "papaya"

hoping for you assistance.

Upvotes: 1

Views: 301

Answers (2)

Dave Sexton
Dave Sexton

Reputation: 11188

You could just treat it as if it is a CSV and do it his way:

Import-Csv ./datafile_in.txt -Delimiter ' ' -Header a, b, c | Select b, c | ConvertTo-Csv -Delimiter ' ' | Select-Object -Skip 1 | Out-File ./datafile_out.txt

Upvotes: 2

AdminOfThings
AdminOfThings

Reputation: 25001

You can do the following:

(Get-Content file.txt) -replace '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}X\s' |
    Set-Content file.txt

-replace uses regex matching. If you provide no replacement string, then the matching strings will just be replaced with empty string. ^ is start of the string. \d is a digit. {number} is a quantifier to repeat the previous regex match number times. - is literal -. \. is a literal ., but it must be backslash escaped because . has special meaning in regex. T is literal but case-insensitive (you can use -creplace for case-sensitive matching). X is literal. : is literal match. \s matches a white space character.

Upvotes: 2

Related Questions