.png)
我有一段文字,例如:
cd123aaq54
我想只分隔另一個文件中的數字,這樣我就可以
12354
在輸出中。
我一直在嘗試很多命令,例如:
Get-Content text.txt | Select-String -Pattern '[0-9]'
在linux下就簡單多了,只要:
grep -o '[0-9][0-9]*' text >numbers
如何在 Windows cmd
shell 中執行此操作?
答案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
進一步閱讀
- Windows CMD 命令列的 AZ 索引- 與 Windows cmd 行相關的所有內容的絕佳參考。
- 對於 /f- 根據另一個指令的結果循環指令。
- 類型- 顯示一個或多個文字檔案的內容。