Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell ,Read from a txt file and Format Data( remove lines, remove blank spaces in between)

Tags:

powershell

I am really very new to powershell. I want to use powershell to read a txt file and change it to another format.

  1. Read from a txt file.
  2. Format Data( remove lines, remove blank spaces in between)
  3. Count of records ( "T 000000002" 9 chars)

and then write the output to a new file.

I just started powershell two days ago so I don't know how to do this yet.

like image 924
user350332 Avatar asked Dec 29 '22 13:12

user350332


1 Answers

  1. Reading from a file:

    Get-Content file.txt
    
  2. Not quite sure what you want here. Get-Content returns an array of strings. You can then manipulate what you get and pass it on. The most helpful cmdlets here are probably Where-Object (for filtering) and ForEach-Object (for manipulating).

    For example, to remove all blank lines you can do

    Get-Content file.txt | Where-Object { $_ -ne '' } > file2.txt
    

    This can be shortened to

    Get-Content file.txt | Where-Object { $_ } > file2.txt
    

    since an empty string in a boolean context evaluates to false.

    Or to remove spaces in every line:

    Get-Content file.txt | ForEach-Object-Object { $_ -replace ' ' } > file2.txt
    
  3. Again, not quite sure what you're after here. Possible things I could think of from your overly elaborate description are something along the lines of

    $_.Substring(2).Length
    

    or

    $_ -match '(\d+)' | Out-Null
    $Matches[1].Length
    
like image 178
Joey Avatar answered Jan 05 '23 00:01

Joey