In Window Batch - how do I remove leading spaces f

2019-09-25 06:54发布

问题:

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
)

回答1:

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


回答2:

@echo off
FOR /F "tokens=* delims= " %%G IN (ttt.txt) DO ECHO %%G|findstr /R /V /C:"^_$">>final.txt

EDIT: Since you are now requesting the line be at least 3 characters long a line with only an underscore at the beginning becomes a mute point. So all you would need is this.

@echo off
FOR /F "tokens=* delims= " %%G IN (ttt.txt) DO >>Final.txt (ECHO %%G|FINDSTR /R /C:"^...")