stringpowershellcsvreplacetxt

remove the first character of each .txt file with Powershell


I have 50 files in a folder that has to be loaded to SQL. In most of the file(but not in all) the very first character is a hashtag that i would like to delete because it creates difficulty in the column mapping.

So I would not want to loop through all the lines of the file just delete the very first character in case it is a hashtag and save the file.

So i need to analyse also if the first character is a hashtag. If it is, then it should be deleted, if it is not, then i should simply exit from the file.

What is the fastest method for this?

I tried these:

$Path = "D:\folder\myfolder"
    $OldText = "#"
    $NewText = ""

--> this loops through all the file looking for hashtags

(Get-Content 'D:\folder\myfoldermyfile.txt' -raw) -replace '^.' | Set-Content 'D:\folder\myfoldermyfile.txt'

--> this removed the first character of each line, so its not good for me.


Solution

  • Because your code uses the -raw switch on Get-Content, you will receive a single multiline string on which you perform the replace.
    In your case, it would be easier to read each file in as string array and replace only the first line in that array.

    Something like this:

    $Path = 'D:\folder\myfolder'
    foreach ($file in (Get-ChildItem -Path $Path)) {
        $content = Get-Content -Path $file.FullName  # read each file as array of lines
        $content[0] = $content[0] -replace '^#'      # remove the hash character in the first line only
        $content | Set-Content -Path $file.FullName
    }
    

    If you first want to test if the very first character is indeed a hash character you could do

    $Path = 'D:\folder\myfolder'
    foreach ($file in (Get-ChildItem -Path $Path)) {
        $content = Get-Content -Path $file.FullName  # read each file as array of lines
        if ($content[0].StartsWith('#')){
            $content[0] = $content[0] -replace '^#'  # remove the hash character in the first line only
            $content | Set-Content -Path $file.FullName
        }
    }