Delete all lines that do not contain "2020" via Batch file

Viewed 621

I have a generated txt file. This file has certain lines that are irrelevant, and need to be excluded. Each line that requires to be removed do not contain the string "2020". I would like to delete these lines, while keeping all other lines.

So txt file like this:

aaa2020
aaa2019
aaa2018
aaa2017

becomes like this:

aaa2020

I have tried

findstr /V "2019" infile.txt > outfile.txt

however that becomes inefficient since I would need to use that command for each incorrect sequence: (2019,2018,2017...)

3 Answers

As your search pattern has no special requirements you may prefer the utility. Open a Command Prompt window, type help find, press the ENTER key and read its usage information.

Using that information you could use:

@find "2020" < "infile.txt" > "outfile.txt"

Or for absolute robustness:

@( ( "%__AppDir__%find.exe" "2020" ) 0< "X:\SomePathTo\infile.txt" ) 1> "Y:\SomeLocation\outfile.txt"

This should be directly transferrable between a or .

Just use findstr without the /V and redirect output to another file:

findstr "2020" infile.txt>output.txt

see findstr /? for more detail on the command usage. Very specifically focus on the line:

/V Prints only lines that do not contain a match.

So what you did was to search for everything, excluding "2019" etc. which would be fine if that is the only thing to exclude. but you have one thing only to include, so rather just find the matching criteria and output the results.

This would find only the lines containing '2020'.

powershell -NoLogo -NoProfile -Command ^
    "(Select-String '2020' 'C:\src\t\infile.txt').Line |" ^
        "Out-File 'C:\src\t\outfile.txt' ascii"

If you want to get all of them at one time, you could...

powershell -NoLogo -NoProfile -Command ^
    "(Select-String '20(17|18|19|20)' 'C:\src\t\infile.txt').Line |" ^
        "Out-File 'C:\src\t\outfile.txt' ascii"
Related