【问题标题】:write PowerShell script to count number of special char and space present in a text file and replace them with tab编写 PowerShell 脚本来计算文本文件中存在的特殊字符和空格的数量,并用制表符替换它们
【发布时间】:2021-08-17 12:19:30
【问题描述】:
  1. 文本文件名“test.txt”

  2. 当前文件内容

    hello!my@name$is*swaraj mohapatra
    11!12#13%14$
    
  3. 所需文件内容

    hello my name is swaraj mohapatra
    11 12 13 14 15
    
  4. 输出:

    This file contains 9 special characters
    

$content = Get-Content "test.txt"
$c = ($b.ToCharArray() -eq '!').count        //can check for only one special character
Write-Output "This file contains $c special characters"
$tab = "`t"
@(ForEach ($line in $b){$a.Replace('  ',$tab).Replace(' ',$tab).Replace('!',$tab)}) > $content
Write-Output "file content without any special char "
$b

【问题讨论】:

    标签: powershell powershell-ise


    【解决方案1】:

    如果您希望替换所有非字母或数字的字符,您可以执行以下操作:

    $content = Get-Content test.txt
    # Matches method will match all occurrences of special characters
    if ($count = [regex]::Matches($content,'[^\p{L}\p{N}]').Count) {
        Write-Output "This file contains $count special characters"
    }
    $UpdatedContent = Set-Content -Value ($content -replace '[^\p{L}\p{N}]',"`t") -Path test.txt -PassThru
    Write-Output "File content without special characters"
    $UpdatedContent
    

    说明:

    由于-replace 使用正则匹配,您可以设置匹配模式和替换字符串。 [^] 是一个与 (^) 内部的任何内容都不匹配的字符类。 \p{L} 匹配一个 unicode 字母。 \p{N} 匹配一个 unicode 数字。每个特殊字符都替换为 PowerShell 选项卡。

    如果您希望将连续的特殊字符替换为单个制表符而不是每个字符一个制表符,您可以使用'[^\p{L}\p{N}]+'仅在替换表达式中,因为我们希望在计数表达式中计算每个单独的特殊字符。 + 匹配一个或多个先前匹配的字符。

    如果您还想替换非英文字母,您可以选择'[^a-zA-Z0-9]' 作为您的正则表达式匹配项。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2021-06-21
      • 2021-03-06
      • 2019-06-01
      • 2013-11-16
      • 2019-08-11
      • 1970-01-01
      • 2013-11-18
      相关资源
      最近更新 更多