nr.iras.sk
nr.iras.sk

Reputation: 8498

batch file programming

I tried to copy one file to another from starting line upto a limit. ie., line 1 to 10(file1.txt)->file2.txt but while writing "!" is skipped. what can i do for to solve it. Any help will be thankful.

The loop for that function is given below.

%NF%-> new file.

%EF%-> existing file

%1% -> line number(passed from another part)

:_doit

findstr /N /R "." %EF%|findstr /B /C:"%1:">nul

if errorlevel 1 (    
    echo. >>%NF%        
) else (    
    for /f "tokens=1 delims=" %%a in ('findstr /N /R "." %EF%^|findstr /B /C:"%1:"') do (    
        if [%%a] EQU [] (    
            echo. >>%NF%    
        ) else (    
            echo %%a >>%NF%    
       )     
   )
)

Upvotes: 4

Views: 673

Answers (4)

nr.iras.sk
nr.iras.sk

Reputation: 8498

if errorlevel 1 ( 
    echo. >>%NF% 
) else ( 
    for /f "tokens=1 delims=" %%a in ('findstr /N /R "." %EF%^|findstr /B /C:"%1:"') do ( 
       if [%%a] EQU [] ( 
          echo. >>%NF% 
       ) else( 
          setlocal DisableDelayedExpansion 
          echo %%a >>%NF%
          endlocal
       ) 
    )
)

Upvotes: 2

jeb
jeb

Reputation: 82410

The reason is the delayed expansion, if you disable it, also the ! work as expected. You can disable it only for the loop.

if errorlevel 1 (    
    echo. >>%NF%        
) else (
   setlocal DisableDelayedExpansion
    for /f "tokens=1 delims=" %%a in ('findstr /N /R "." %EF%^|findstr /B /C:"%1:"') do (    
        if [%%a] EQU [] (    
            echo. >>%NF%    
        ) else (    
            echo %%a >>%NF%    
       )     
   )
   endlocal
)

The parser for batch lines has multiple phases: The first phase is the %var% expansion, then comes the special character phase "^<>&|() and after the %%a phase, the delayed (exclamation phase).

That's the reason why the ! dissappear in your case. Because you got something like this from your file %%a=Hello! Then the exclamation phase try to expand the !, but this fails and it is removed.

If in your file is the line Hello^! you got in your "copy" Hello!

But in a batch file you need two carets to display one !

echo hello^^!

Because in phase2, the ^^! is inflated to ^!, and in the exclamation phase the last caret escapes the !

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 343057

If you can download tools, you can use GNU win32 gawk

gawk.exe "NR>10{exit}1"  file1 > file2

And you can take a look at this thread here that is similar

Upvotes: 3

Benoit
Benoit

Reputation: 79233

Maybe use gawk.exe from UnxUtils :

gawk "NR<10" < file1 > file2

Upvotes: 1

Related Questions