2

I am very new to batch scripting. I don't have much knowledge about Batch Scripting.

My doubt is how to copy only some line from text file to other text file.

Say my File.txt is

This is sample file.
I want copy this line.
Also this line.
But not this line.

I want to copy line 2 and 3, but not using their line number, because may change.

This muchI have done till now:

@ECHO OFF
SET InFile=abc.txt
SET OutFile=Output.txt
IF EXIST "%OutFile%" DEL "%OutFile%"
SET TempFile=Temp.txt
IF EXIST "%TempFile%" DEL "%TempFile%"

IF EXIST "%OutFile%" DEL "%OutFile%"

FOR /F "tokens=*" %%A IN ('FINDSTR "I want" "%InFile%"') DO (
    ECHO.%%A> "%TempFile%"
    ECHO.%TempFile%>>"%OutFile%"
REM CALL :RemovePrecedingWordA "%%A"
    )
FOR /F "tokens=*" %%A IN ('FINDSTR " Also this" "%InFile%"') DO (
    ECHO.%%A> "%TempFile%"
    ECHO.%TempFile%>>"%OutFile%"
REM CALL :RemovePrecedingWordA "%%A"
    )

But its not working. Please help.

2 Answers 2

7

You could use the /g: option to findstr, basically do

findstr /g:pattern.txt %InFile% > %OutFile%

where pattern.txt is (in your example)

I want
Also this

This assumes you can write findstr regular expressions for all the lines you want to copy.

If you use findstr with multiple files (wildcard) you will get the file name prepended. To get round this, use del out.txt for %F in (*.txt); do findstr /g:pattern.txt %F >> out.txt Note that you should put the source files in a different directory to the pattern and output files (or use a different extension) otherwise the *.txt wildcard will pick those files up, too.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Peter, is there any way to remove the file path while using wildcard "c:*.txt". My output will show "c:\test.txt: Blablabla" rather than "Blablabla". Thanks in advanced.
@Nyc2x not straightforward but see the edit to my post - is that what you mean? Otherwise, asking a new question might be better.
1

You can also use sed for this purpose. Certain lines (in this case 2 and 3) are copied as follows:

sed -n -e 2p -e 3p input.txt > output.txt

If you wish to copy a segment of lines (all lines from line 2 to line 10) then you may use:

sed -n -e 2,10p input.txt > output.txt

Or you can also use combinations of certain lines and segments:

sed -n -e 2,10p -e 15p -e 27p input.txt > output.txt

1 Comment

the question states: "but not using their line number, because may change."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.