Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

cmd - In Window Batch - how do I remove leading spaces from a file?

I have a file, ttt.txt. The content/format is like this:

  AAA BBB
  AAA CCC
  _
  CCC DDD
  1. There are 2 leading spaces on each line;
  2. There are some lines with only 1 understore sign>

I need to:

  1. remove those empty lines with only 1 understore sign (_);
  2. I need to trim leader spaces for each line.

Here is my current script:

:: ===== Here to underscore lines
type ttt.txt |  findstr /v "^_"  >Final.txt

@echo off
setlocal enabledelayedexpansion

for /F "tokens=*" %%A in (ttt.txt) do (
    set line=%%A
echo(!line:~1!>>myFinal.txt
)
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When processing text files, the FOR processing will automatically remove leading spaces. So the only thing you really have to do is simply check if the line value is equal to an underscore and, if so, ignore it.

@ECHO OFF
SETLOCAL

FOR /F "tokens=*" %%A IN (ttt.txt) DO (
    IF NOT "%%A"=="_" ECHO %%A>>myFinal.txt
)

ENDLOCAL

Edit: Per your changed requirements, the following would verify the length is 3 or longer as well.

@ECHO OFF
SETLOCAL EnableDelayedExpansion

FOR /F "tokens=*" %%A IN (ttt.txt) DO (
    SET Line=%%A

    REM Verify it is not an underscore.
    IF NOT "!Line!"=="_" (

        REM Check that the length is 3 chars or longer.
        SET Char=!Line:~2,1!
        IF NOT "!Char!"=="" (

            REM All conditions satisfied.
            ECHO %%A>>myFinal.txt
        )
    )
)

ENDLOCAL

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...