Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

Batch command to find a replace string with line break

I have data that is mostly organized in a way that I can convert and import into a spreadsheet. But certain lines have carriage returns and text that my current batch file won't use.

Good Data:

Pipers Cove × 2   $25.00
Pipers Cove Petite × 2    $25.00
Pipers Cove Plus × 2  $25.00
Nordic Club × 2   $25.00
Whiteout × 1  $12.50

Bad Data:

Pipers Cove Kids × 2
Size:
Large - ages 10 to 12
$20.00
Pipers Cove Kids × 2
Size:
Medium - ages 6 to 8
$20.00
Pipers Cove Kids × 2
Size:
Small - ages 2 to 4
$20.00

I need to remove the 2 lines starting with Size, Small, Medium, or Large and have the dollar amount follow the quantity number so my batch file can convert it to a CSV file and so on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@ECHO OFF
SETLOCAL
SET "sourcedir=U:sourcedir"
SET "destdir=U:destdir"
SET "filename1=%sourcedir%q40953616.txt"
SET "outfile=%destdir%outfile.txt"
SET "part1="
(
FOR /f "usebackqdelims=" %%i IN ("%filename1%") DO (
 ECHO %%i|FIND "$" >NUL
 IF ERRORLEVEL 1 (
  REM $ not found - set part1 on first such line
  IF NOT DEFINED part1 SET "part1=%%i"
  ) ELSE (
  REM $ found - see whether at start or not
  FOR /f "tokens=1*delims=$" %%a IN ("%%i") DO (
   IF "%%b"=="" (
    REM at start - combine and output and reset part1
    CALL ECHO %%part1%% %%i
    SET "part1="
   ) ELSE (
    ECHO %%i
   )
  )
 )
)
)>"%outfile%"

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q40953616.txt containing your data for my testing.

Produces the file defined as %outfile%

Scan each line of the file. If the line does not contain $ then save the first such line in part1.
Otherwise, tokenise the line. If there is only 1 token, then the $ is at the start of the line, so it needs to be output combined with part1
Otherwise, just regurgitate the line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...