1

Team,

I have a file in Windows where the content is like the below:

460 ls

461 cd ..

462 ls

463 cd ubuntu/

464 ls

465 cd test/

466 ls

467 cd ..

468 openvpn

I want to remove all the numbers which are present in the beginning and get the actual content.

I have tried :

$var= Get-Content C:\Scripts\test.txt
$var.replace("/[4 6]/","");

$var.replace("/[4 6]/","");

($var.replace("4","")).Replace("6","")

But is it possible to get some regular expression solution for this.

3
  • 1
    $var -replace '^[\s\d]+',''? Commented Dec 19, 2017 at 8:26
  • @Wiktor Stribiżew Smaller : $var -replace '^[\s\d]+' (no need to add the second argument with -replace if it's a removal) Commented Dec 19, 2017 at 8:30
  • @Manu Thanks for the tip. Commented Dec 19, 2017 at 8:46

2 Answers 2

6

When processing a file line by line you may use the following pattern:

$var -replace '^[\s\d]+'

See the regex demo

When processing a whole file as one string you would need to use

$var -replace '(?m)^[\p{Zs}\t\d]+'

in order not to overflow across lines. See a .NET regex demo.

Details

  • ^ - start of the input (when (?m) is used at the start of the pattern, ^ matches start of input and start of each line)
  • [\s\d]+ - one or more whitespaces (\s) or digits (\d)
  • [\p{Zs}\t] - matches any horizontal whitespace.

enter image description here

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

2 Comments

@RanadipDutta: Sorry, I meant (?m)^[\p{Zs}\t\d]+ of course, mixed up \s and \d. I updated the answer.
Worked neatly. Both of them . Thank you
1

You can do so by using the following regular expression.

$result = $var -replace '^[\s]?\d+'

To update the file with the $result you can use the code below.

Set-Content -Value $result -Path C:\Scripts\test.txt

7 Comments

$var -replace '^\d+' is not working. It gave me the same output
@RanadipDutta when I execute $var -replace '^\d+' it returns the content without numbers as you asked for. To update the content of the file you have to assign the result to a variable like I did (i.e. result). Afterwards the content of the file has to be overriden by using the second statement I posted into my answer.
I did that. But that regex is not working. That I tried even earlier also.
@RanadipDutta do your lines in the text file start with a space?
The reason why it is not working is because I have leading spaces which you are not covering. I have mentioned that in the question. It is working with '^[\s\d]+'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.