locked
split foreach line. RRS feed

  • Question

  • Hi,

    Im trying to do a script which add a hyphen after every each 2 characters which is in a text file, and i have done it but im facing an issue which is.

    Code >

    $file = get-content .\textfile.txt
    ($file -split "([a-z0-9]{2})"  | ?{ $_.length -ne 0 }) -join "-" | Set-Content .\textfile.txt

    If i have a value like below in a .txt file

    000000000000

    111111111111

    Output is coming like.

    00-00-00-00-00-00-11-11-11-11-11-11

    I need an output like.

    00-00-00-00-00-00

    11-11-11-11-11-11

    Kindly suggest what shud i have to change .

    Thanks and Regards,

    Abdul.


    • Edited by meow_tuff Wednesday, September 5, 2018 4:15 AM
    Wednesday, September 5, 2018 4:14 AM

Answers

  • This will add a dash (-) after every two characters in a line. Since it will also do this at the end of a line, we trim it.

    $inputFile = Get-Content -Path C:\temp\file.txt
    
    $newFile = foreach ($line in $inputFile) {
       ($line -replace '(..)', '$1-').trim('-')
    } 
    
    $newFile | Set-Content -Path C:\temp\file.txt


    • Edited by John Seerden Wednesday, September 5, 2018 5:31 AM
    • Marked as answer by meow_tuff Wednesday, September 5, 2018 5:35 AM
    Wednesday, September 5, 2018 5:31 AM

All replies

  • Index the string by 2's  then output like this:

    ('0000000000'.ToCharArray()[0..1]) -join ''


    \_(ツ)_/

    Wednesday, September 5, 2018 4:25 AM
  • Please be a bit specific , the txt file will be having more than 100 string with 12 characters. can u help me what modification i shud make in to do the split untill 12 characters or end of line.

    Wednesday, September 5, 2018 5:15 AM
  • This will add a dash (-) after every two characters in a line. Since it will also do this at the end of a line, we trim it.

    $inputFile = Get-Content -Path C:\temp\file.txt
    
    $newFile = foreach ($line in $inputFile) {
       ($line -replace '(..)', '$1-').trim('-')
    } 
    
    $newFile | Set-Content -Path C:\temp\file.txt


    • Edited by John Seerden Wednesday, September 5, 2018 5:31 AM
    • Marked as answer by meow_tuff Wednesday, September 5, 2018 5:35 AM
    Wednesday, September 5, 2018 5:31 AM
  • Thanks alot , it worked :) 
    Wednesday, September 5, 2018 5:35 AM