使用单个Windows命令从文件中提取N行

use*_*292 12 windows cmd command-prompt

有没有办法从文件中提取/复制第一行X行,并使用windows命令提示符使用单个命令将它们输入到另一个文件中?

我可以使用以下内容删除第一行X行:
more + X [file_containing data]> [file_to_export_data_to]

如果head命令可以工作,我想我可以这样做:
head -X [file_containing data]> [file_to_export_data_to]

但不幸的是,这不起作用.

如果Windows有一个"较少"的命令,但再次没有运气,那将是很好的.

当谈到这些东西时,我是一个完全的新手,所以我肯定我错过了一些明显的东西.我不想安装任何东西或使用命令提示符以外的东西.

谢谢

Jan*_*usz 20

最简单的单命令解决方案是使用Powershell Get-Content.

N - 行数.

从文件的开头:

Get-Content -Head N file.txt
Run Code Online (Sandbox Code Playgroud)

从文件末尾:

Get-Content -Tail N file.txt
Run Code Online (Sandbox Code Playgroud)

  • 我得到"找不到匹配参数名称'Head'的参数." 错误. (2认同)
  • 您可能必须使用“ TotalCount”而不是“ Head”。请参阅https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/get-content?view=powershell-6 (2认同)

dbe*_*ham 17

您可以从cmd.exe控制台使用PowerShell:

 powershell -command "& {get-content input.txt|select-object -first 10}" >output.txt
Run Code Online (Sandbox Code Playgroud)

您可以创建一个DOSKEY宏,以便从命令行更容易使用:

doskey head=powershell -command "& {get-content $1|select-object -first $2}"
Run Code Online (Sandbox Code Playgroud)

用法:

head input.txt 10 >output.txt
Run Code Online (Sandbox Code Playgroud)

但是您不能在批处理脚本中使用DOSKEY宏.

您可以创建head.bat脚本,并将其放在PATH中包含的文件夹中:

head.bat

@powershell -command "& {get-content %1|select-object -first %2}"
Run Code Online (Sandbox Code Playgroud)

从命令行,您将使用 head input.txt 10 >output.txt

在批处理脚本中,您将使用 call head input.txt 10 >output.txt

我选择不将输出文件作为参数,以防您只想将结果显示在屏幕上而不是写入文件.


小智 1

Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
x = 0
    Do Until Inp.AtEndOfStream
              x = x + 1
        OutP.WriteLine Inp.Readline
              If x = 5 then Exit Do
    Loop
Run Code Online (Sandbox Code Playgroud)

这将打印第 1 行到第 5 行。

cscript //nologo <path to script.vbs> <inputfile >outputfile
Run Code Online (Sandbox Code Playgroud)