Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first line from a text file with cmd?

This is my text file and I want to remove first line (with blank):

abc!
def  #
ghi./;
jklm
nopqrs

How can I remove first line from my text file?

I want my second line be first line:

def  #
ghi./;
jklm
nopqrs

I tried findstr command, but it doesn't work.

like image 815
Ali Alias Avatar asked Dec 17 '22 23:12

Ali Alias


2 Answers

The easiest approach (assuming your text file is called data.txt):

more +1 "data.txt" > "data_NEW.txt"

This limits lines to a length of about 65535 bytes/characters and the file to about 65535 lines. Furthermore, TABs become expanded to SPACEs (8 by default).


You could use a for /F loop instead (the odd-looking unquoted option string syntax is needed here in order to disable the default eol character ; to not ignore lines beginning with such):

@echo off
(
    for /F usebackq^ skip^=1^ delims^=^ eol^= %%L in ("data.txt") do echo(%%L
) > "data_NEW.txt"

This limits lines to a length of about 8190 characters/bytes and loses empty lines.


You could use a for /F loop together with findstr to keep empty lines (findstr adds a line number plus : to each line, so for /F does not see empty lines; everything up to the (first) colon is then removed in the loop body; toggling delayed expansion ensures not to lose !):

@echo off
(
    for /F "skip=1 delims=" %%L in ('findstr /N "^" "data.txt"') do (
        set "LINE=%%L"
        setlocal EnableDelayedExpansion
        echo(!LINE:*:=!
        endlocal
    )
) > "data_NEW.txt"

This still limits lines to a length of about 8190 characters/bytes.


Or you could use input redirection < together with set /P (for this the total number of lines needs to be determined in advance):

@echo off
for /F %%C in ('find /C /V "" ^< "data.txt"') do set "COUNT=%%C"
setlocal EnableDelayedExpansion
(
    for /L %%I in (1,1,%COUNT%) do (
        set "LINE=" & set /P LINE=""
        if %%I gtr 1 echo(!LINE!
    )
) < "data.txt" > "data_NEW.txt"
endlocal

This limits lines to a length of about 1022 characters/bytes.


To replace your original file with the modified one, simply do this:

move /Y "data_NEW.txt" "data.txt" > nul
like image 134
aschipfl Avatar answered Feb 04 '23 09:02

aschipfl


From the prompt,

for /f "skip=1delims=" %a in (yourtextfilename) do >>anoutputfilename echo %a

where yourtextfilename & anoutputfilename must be different filenames and need to be "quoted" if they contain spaces or other separators.

like image 37
Magoo Avatar answered Feb 04 '23 10:02

Magoo