ella_m
ella_m

Reputation: 33

Replace first and last character of each line in file

I have a file and need to replace the fist and last character of each line. I don't know how many lines the file has.

This is what I got so far:

$original_file = 'test.csv'
$destination_file =  'new.cvs'

$a = Get-Content $original_file
$i = $a.Length
$b = ""
$j = 0

if($j -ne $i) {
    $j = $j + 1
    $z = Get-Content $a | Select-Object -Index $j
    $z.replace (0, '$')
    $z.replace (z.Length, '$')
    $b = $b + $z
}

Set-content -path $destination_file -value $b

But it doesn't work. What am I doing wrong?

Upvotes: 3

Views: 7813

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

You're overcomplicating things. Simply use a regular expression:

$original_file    = 'test.csv'
$destination_file = 'new.cvs'

(Get-Content $original_file) -replace '^.|.$', '$' |
  Set-Content $destination_file

^. matches the first character in a string, .$ matches the last one. | in a regular expression means an alternation, i.e. "match any of the alternatives in this pipe-separated list".

Upvotes: 6

Related Questions