在經典 Windows CMD 中僅過濾輸出中的數字 (0-9)

在經典 Windows CMD 中僅過濾輸出中的數字 (0-9)

我有一段文字,例如:

cd123aaq54

我想只分隔另一個文件中的數字,這樣我就可以

12354

在輸出中。

我一直在嘗試很多命令,例如:

Get-Content text.txt | Select-String  -Pattern '[0-9]'

在linux下就簡單多了,只要:

grep -o '[0-9][0-9]*' text >numbers

如何在 Windows cmdshell 中執行此操作?

答案1

如何從輸入檔中去除字母字符,只留下數字?

下面給出兩種解決方案:

  • 電源外殼
  • Windows 批次檔

PowerShell解決方案

使用以下命令:

Get-Content input.txt | ForEach-Object {$_ -Replace "[^0-9]", ""} > output.txt

筆記:

  • input.txt包含要過濾的文字。

  • output.txt包含過濾後的文本

  • 所有非數字字元(不僅僅是字母字元)都將被刪除。

例子:

PS F:\test> type .\input.txt
cd123aaq54
zyx456abc321
PS F:\test> Get-Content input.txt | ForEach-Object {$_ -Replace "[^0-9]", ""} > output.txt
PS F:\test> type .\output.txt
12354
456321
PS F:\test>

Windows批次檔解決方案

使用以下批次檔 (RemoveAlpha.cmd):

@echo off
setlocal enabledelayedexpansion
set _alpha=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
rem read input file line by line
for /f "usebackq tokens=*" %%i in (`type %1`) do (
  rem strip alpha characters by using them as delimeters
  for /f "tokens=1,2 delims=%_alpha%" %%j in ("%%i") do (
    rem write stripped text to output file
    echo %%j%%k>>%2
    )  
  )
endlocal

筆記:

  • 上面假設輸入檔中沒有特殊字元(!@#$%^&*()...)(它們不會被刪除)。

  • 「技巧」是使用 Alpha 字串作為第二個for指令的分隔符號。

用法:

RemoveAlpha input output
  • input:包含要過濾的文字的輸入檔的路徑名。

  • output:包含複製的篩選器文字的輸出檔案的路徑名。

例子:

F:\test>RemoveAlpha input.txt output.txt

F:\test>type input.txt
cd123aaq54
zyx456abc321

F:\test>type output.txt
12354
456321

進一步閱讀

相關內容