简体   繁体   中英

skip header line and replace string in text file in batch script

@echo off     
setlocal enableextensions disabledelayedexpansion    
for /r %f in (xis_a*) do  More +1 %~nxf >> No_header_%~nxf    
set "search=:20:"

    set "replace={:20:"
    for /f "delims=" %%i in ('type (No_header_*.txt) ^& break ^> (No_header_*.txt) ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:%search%=%replace%!"
        >>No_header_*.txt echo(!line!
        endlocal
    )

am trying to skip the header line in a text file and replace :20: with {:20:. i have written and have achieved almost.. please try to help me am totally new to this

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
set "search=:20:"
set "replace={:20:"

for /r "%sourcedir%" %%f in (xis_a*) do (
 REM DEL "%destdir%\No_header_%%~nf.txt" >NUL 2>nul
 for /f "usebackqskip=1delims=" %%i in ("%%f") do (
  set "line=%%i"
  setlocal enabledelayedexpansion
  set "line=!line:%search%=%replace%!"
  >>"%destdir%\No_header_%%~nf.txt" echo(!line!
  ENDLOCAL
 )
)

GOTO :EOF

This should solve the problem.

In your code, the initial setlocal is establishing the default condition, so I omitted it.

You have %f in your 'for /r - the % before the metavariable f needs to be doubled.

The more ceremony isn't required - for /f has a skip option which will allow the first n lines to be skipped.

So - all that is required is to get the list of files generated by the for...%%f... loop and with each, process each individual file, skipping the first line. Quoting the filename appearing in %%f is simply a safety-measure to allow for filenames containing separators, but this means that usebackq needs to be invoked to tell for /f that the list given is not a literal string (which it will assume for a "quoted string,") but a filename.

Then, since %%f is in-context for the %%i loop, you can select the target filename by using %%~nf . I'm not sure whether you want ~nf or ~nxf (adding a second .txt extension) so I elected to use ~n alone. Note that your use of * is doomed - that means "all files matching" - probably not quite what you want, and cmd will get very confused.

I've aded a remmed-out del command to allow the destination file to be deleted - just remove the rem if required, otherwise the data will be appended to any exiating file.

I use my u: drive for testing, and have left my source and destination names in place. No doubt you would need to change those to suit your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM