【问题标题】:Replace first and last character of each line in file替换文件中每一行的第一个和最后一个字符
【发布时间】:2015-03-28 13:51:43
【问题描述】:

我有一个文件,需要替换每行的第一个字符和最后一个字符。我不知道文件有多少行。

这是我目前得到的:

$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

但它不起作用。我做错了什么?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请注意:告诉我们脚本当前的作用(错误输出、错误消息)可能有助于我们给出答案。

标签: powershell replace character


【解决方案1】:

你把事情复杂化了。只需使用正则表达式:

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

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

^. 匹配字符串中的第一个字符,.$ 匹配最后一个字符。正则表达式中的| 表示替代,即“匹配此管道分隔列表中的任何替代”。

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2014-05-13
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多