简体   繁体   English

如何使用批处理脚本获取文本文件的每第三行并将其放在单独的文本文件中

[英]How to get every 3rd line of text file and put it on a separate text file using batch script

I need to get only the every 3rd line of a text file(Movie.txt) and put it on a separate text file(Title.txt) using batch script(for /f)我只需要获取文本文件(Movie.txt)的每第三行,并使用批处理脚本(for /f)将其放在单独的文本文件(Title.txt)上

Movie.txt电影.txt

 Movie
  Title
  Anime1
Movie
  Title
  Anime2
Movie
  Title
  Anime3
Movie
  Title
  Anime4

Title.txt标题.txt

Anime1
Anime2
Anime3
Anime4

currently I have no idea how to get the required data... I would appreciate any help you can provide.目前我不知道如何获得所需的数据......我很感激你能提供的任何帮助。 thank you.谢谢你。

@echo off
setlocal enabledelayedexpansion
set input=yourinput.txt
set output=youroutput.txt
set i=0
for /f "tokens=*" %%l in (%input%) do (
    set /a i=!i!+1
    set /a r=!i!%%3
    if !r!==0 echo %%l>>%output%
)

We can use the modulo operator and a line counter.我们可以使用模运算符和行计数器。 !i! contains the line number and !r!包含行号!r! is the line number modulo 3 .模 3行号 So if !r!==0 we write the line ( %%l ) into the output file.因此,如果!r!==0我们将这一行 ( %%l ) 写入输出文件。

@ECHO OFF
SETLOCAL
SET "line1="
SET "line2="
FOR /f "tokens=1*delims=" %%a IN (
 'findstr /r "." "100lines.txt"'
 ) DO (
 IF DEFINED line1 (
  IF DEFINED line2 (
   ECHO %%a
   SET "line1="
   SET "line2="
  ) ELSE SET line2=y
 ) ELSE SET line1=y
)
GOTO :EOF

All you need is to replace the input filename - I have a file named 100lines.txt that contains 100 different lines of text.您只需要替换输入文件名 - 我有一个名为100lines.txt的文件,其中包含 100 行不同的文本。

Since a variable's current defined status acts on the run-time value of the variable, ensure that the two flags are clear to start, then for each line of the file,由于变量的当前defined状态作用于变量的run-time时值,因此确保两个标志清除启动,然后对于文件的每一行,

if line1 is not defined, set it如果line1未定义,则设置它
otherwise, if line2 is not defined, set it否则,如果line2未定义,则设置它
otherwise we are on a *3 line, so regurgitate it and clear the two flags.否则我们在*3线上,所以反刍它并清除两个标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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