How can I strip Alpha characters from an input file, leaving only numbers?
Below are two solutions:
- PowerShell
- Windows batch file
PowerShell solution
Use the following command:
Get-Content input.txt | ForEach-Object {$_ -Replace "[^0-9]", ""} > output.txt
Notes:
input.txt
contains the text to be filtered.
output.txt
contains the filtered text
All non numeric characters (not just alpha characters) will be removed.
Example:
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 batch file solution
Use the following batch file (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
Notes:
The above assumes there are no special characters (!@#$%^&*()
...) in the input file (they won't be removed).
The 'trick' is to use the string of Alpha characters as delimeters for the second for
command.
Usage:
RemoveAlpha input output
Example:
F:\test>RemoveAlpha input.txt output.txt
F:\test>type input.txt
cd123aaq54
zyx456abc321
F:\test>type output.txt
12354
456321
Further Reading
grep
, though not all have the-o
option.bash.exe
itself very much, but in a 5.6MB zip file, as well asbash
, there are over 100 of the common Unix utilities, includingsed
,wget
,find
,xargs
and of coursegrep
, and this version supports-o
. There is no installation: extract to a directory, add it to yourPATH
and then run as required. Or you can add selected utilities to an existing directory already in your path. They are all 32-bit implementations, which means they will run on any Windows system since 98. Sadly there is noman
.Get-Content
is a powershell command, not cmd