Search code examples
windowsbatch-filecmdfindstr

Delete textline with findstr


I have moved the file which has lines starting with specific text through the code below.

It was possible until this, but I want to delete the text except for the lines with only specific text,

but I don't know what to do.

for /f %%a in ('findstr /b /m "a" *.txt') do (
        move /y "%%~a" "D:change_text"
        )

Below is an example of the text.

ex1)

b 0.d4g7a6 0.4g1h5s 0.b9g5r2 0.6s7d2f

a 0.6d7g1a 0.6g1g8a 0.6z4s6f 0.g7w2a7x

to

a 0.6d7g1a 0.6g1g8a 0.6z4s6f 0.g7w2a7x

ex2)

d 0.5g98 0.6b3n8 0.3s4q2a 0.s3z6d9f
a 1.6g2 0.5c9d4 0.1a7ge2z 0.1fe4sz6x
a 0.3q8t6e 0.5q8r6q 2.1a4zx9vs 0.1q2s6c
z 0.6p2o3t 0.e9 0.1q8s6z 0.v0s9d4f
a 0.7i6i1l 0.6u9q4 0.0c2v9 0.0z5s5d
a 0.9q3z 0.6s7d6f 0.0w3s9f 0.h0y1y8u

to

a 1.6g2 0.5c9d4 0.1a7ge2z 0.1fe4sz6x
a 0.3q8t6e 0.5q8r6q 2.1a4zx9vs 0.1q2s6c
a 0.7i6i1l 0.6u9q4 0.0c2v9 0.0z5s5d
a 0.9q3z 0.6s7d6f 0.0w3s9f 0.h0y1y8u

tell me opinions

Okay to tell in other languages.


Solution

  • Well, findstr only finds text but it does not remove text from a file. You are searching for files that contain specific text and then move them somewhere, so you are missing the step where text actually becomes removed. You could do this:

    rem /* Search files that contain matching text and loop through them;
    rem    since the `/M` option is specified the file names are returned;
    rem    the search string `^a\>` searches the word `a` at the beginning
    rem    of the line (`^`), `\>` constitutes a word boundary: */
    for /F "delims= eol=|" %%F in ('findstr /M "^a\>" "*.txt"') do (
        rem /* Search the current file again but return the matching text this time;
        rem    write that text to another file using redirection (`>`);
        rem    if successful (`&&`), delete the current (original) file: */
        (> "D:\%%~F" findstr "^a\>" "%%~F") && del "%%~F"
    )