简体   繁体   中英

Count number of occurrence of character for each file (first line only)

I have a folder that contains a bunch of csv files.

I would like to make a Powershell script that is able to read the first line of each file in that folder and count the number of occurence of a specific character within that line (a semicolon in my case).

The desired output file would be :

File_1 : 6 --number of semicolons in the 1st line of the 1st file
File_2 : 8  --number of semicolons in the 1st line of the 2nd file
File_3 : 13  --number of semicolons in the 1st line of the 3rd file
...

You can break this down as:

  • Discover all the files
  • For each of them:
    • Read first line
    • Count semicolons
    • Output file name + count
# Discover the files
$csvFiles = Get-ChildItem C:\path\to\folder\*.csv

foreach($file in $csvFiles){
  # Read first line
  $firstLine = $file |Get-Content -TotalCount 1

  # Remove anything that's NOT a semicolon - resulting length is the count
  $firstLine = $firstLine -replace '[^;]'

  # output file name and count
  [pscustomobject]@{
    Filename = $file.Name
    Count = $firstline.Length
  }
}

接受的答案似乎有点不必要的复杂,所以这里是一个 Powershell one liner:

Get-Childitem -Filter *.csv | % {$_ | Add-Member -Name Count -MemberType NoteProperty -Value ([regex]::Matches((Get-Content $_.Name -TotalCount 1), ':').Count); $_} | Select Name, Count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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