基于Windows Power Shell的文字处理工具

基于Windows Power Shell的文字处理工具

# 文字处理工具

function Show-Menu {

Clear-Host

Write-Host "文字处理工具"

Write-Host "1. 打开文件并显示内容"

Write-Host "2. 查找并替换文本"

Write-Host "3. 统计单词数量"

Write-Host "4. 统计字符数量"

Write-Host "5. 退出"

}

function Open-File {

param (

[string]$filePath

)

if (Test-Path $filePath) {

$content = Get-Content $filePath

Write-Host "文件内容:"

Write-Host $content

} else {

Write-Host "文件不存在!"

}

}

function Find-And-Replace {

param (

[string]$filePath,

[string]$findText,

[string]$replaceText

)

if (Test-Path $filePath) {

$content = Get-Content $filePath

$newContent = $content -replace $findText, $replaceText

Set-Content $filePath $newContent

Write-Host "文本已被替换"

} else {

Write-Host "文件不存在!"

}

}

function Count-Words {

param (

[string]$filePath

)

if (Test-Path $filePath) {

$content = Get-Content $filePath -Raw

$wordCount = ($content -split '\s+').Length

Write-Host "单词总数: $wordCount"

} else {

Write-Host "文件不存在!"

}

}

function Count-Characters {

param (

[string]$filePath

)

if (Test-Path $filePath) {

$content = Get-Content $filePath -Raw

$charCount = $content.Length

Write-Host "字符总数: $charCount"

} else {

Write-Host "文件不存在!"

}

}

# 主程序

do {

Show-Menu

$choice = Read-Host "请输入你的选择"

switch ($choice) {

1 {

$filePath = Read-Host "请输入文件路径"

Open-File -filePath $filePath

}

2 {

$filePath = Read-Host "请输入文件路径"

$findText = Read-Host "请输入要查找的文本"

$replaceText = Read-Host "请输入要替换的文本"

Find-And-Replace -filePath $filePath -findText $findText -replaceText $replaceText

}

3 {

$filePath = Read-Host "请输入文件路径"

Count-Words -filePath $filePath

}

4 {

$filePath = Read-Host "请输入文件路径"

Count-Characters -filePath $filePath

}

5 {

Write-Host "退出工具..."

break

}

default {

Write-Host "无效选择,请重新输入"

}

}

Read-Host "按 Enter 键继续..."

} while ($true)