BillytheKid
BillytheKid

Reputation: 43

Batch Scripting:search file, extract numbers, and copy into new file

I'm new to batch scripting and have a question. I was wondering if it's possible to search a .txt file by requirements and take data specified and copy into a new .txt file?

Like if I have 50 lines with 9 digit numbers and a bunch of other crap I don't need after them can I say, "For any line beginning with a 1,2,3,4,5,6,7,8,or 9...take the first 9 digits and copy them into a new file, for all lines in the file???"

I thought this would be easier than trying to delete all the other stuff. Let me know if you know anything about how to do this! Thanks.

Here's an example of what one line looks like:
123456789@example
and I just need to extract the 9 digit numbers from about 50 lines of this.

Upvotes: 1

Views: 2157

Answers (3)

dbenham
dbenham

Reputation: 130819

You can use FINDSTR to filter out all lines that do not start with 9 digits. Then FOR /F can read the result, line by line. A variable is set, and a substring operation preserves just the first 9 digits.

@echo off
setlocal enableDelayedExpansion
(
  for /f %%A in (
    'findstr "^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" yourFile.txt'
  ) do (
    set "ln=%%A"
    echo !ln:~0,9!
  )
)>newFile.txt

Upvotes: 1

Magoo
Magoo

Reputation: 79983

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
(
FOR /f "delims=" %%a IN (q24824079.txt) DO (
 SET "line=%%a"
 REM set DIGITS to the first 9 characters of LINE
 SET "digits=9!line:~0,9!"
 FOR /L %%z IN (0,1,9) DO SET "digits=!digits:%%z=!"
 IF NOT DEFINED digits ECHO(!line:~0,9!
)
)>newfile.txt

GOTO :EOF

I used a file named q24824079.txt containing data for my testing. Produces newfile.txt

You did not specfy what to do if the line was all-digits but has fewer than 9 characters. I chose to report that line.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59238

Hopefully this helps getting the job done:

@echo off
setlocal enabledelayedexpansion
for /f %%e in (emails.txt) do (
    echo Email: %%e
    for /f "delims=@ tokens=1" %%b in ("%%e") do (
        set BEGIN=%%b
        echo Name: !BEGIN!
        set FIRST=!BEGIN:~0,1!
        echo First char: !FIRST!
        set /a NUMERIC=!FIRST!+0
        echo Converted to number: !NUMERIC!
        if !FIRST!==!NUMERIC! echo Yippieh!
        echo.
    )
)

Instead of echo Yippieh! append the email (%%e) to a file, e.g. like

echo %%e >> output.txt

Upvotes: 0

Related Questions