PowerShell get number of lines of big (large) file

前端 未结 8 1209
小鲜肉
小鲜肉 2020-12-23 16:35

One of the ways to get number of lines from a file is this method in PowerShell:

PS C:\\Users\\Pranav\\Desktop\\PS_Test_Scripts> $a=Get-Content .\\sub.ps1         


        
8条回答
  •  清酒与你
    2020-12-23 17:09

    Here is a one-liner based on Pseudothink's post.

    Rows in one specific file:

    "the_name_of_your_file.txt" |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
    

    All files in current dir (individually):

    Get-ChildItem "." |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
    

    Explanation:

    "the_name_of_your_file.txt" -> does nothing, just provides the filename for next steps, needs to be double quoted
    |% -> alias ForEach-Object, iterates over items provided (just one in this case), accepts piped content as an input, current item saved to $_
    $n = $_ -> $n as name of the file provided is saved for later from $_, actually this may not be needed
    $c = 0 -> initialisation of $c as count
    Get-Content -Path $_ -ReadCount 1000 -> read 1000 lines from file provided (see other answers of the thread)
    |% -> foreach do add numbers of rows actually read to $c (will be like 1000 + 1000 + 123)
    "$n; $c" -> once finished reading file, print name of file; count of rows
    Get-ChildItem "." -> just adds more items to the pipe than single filename did

提交回复
热议问题