ell*_*a_m 3 powershell replace character
我有一个文件,需要替换每一行的拳头和最后一个字符。我不知道文件有多少行。
这是我到目前为止所得到的:
$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
Run Code Online (Sandbox Code Playgroud)
但这是行不通的。我究竟做错了什么?
您太复杂了。只需使用一个正则表达式:
$original_file = 'test.csv'
$destination_file = 'new.cvs'
(Get-Content $original_file) -replace '^.|.$', '$' |
Set-Content $destination_file
Run Code Online (Sandbox Code Playgroud)
^.匹配字符串中的第一个字符,.$匹配最后一个字符。|正则表达式中的“替换”表示“匹配此管道分隔列表中的任何替代项”。
| 归档时间: |
|
| 查看次数: |
4950 次 |
| 最近记录: |