Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting Windows CMD中文本文件行的Groupby和count_Sorting_Cmd_Grouping - Fatal编程技术网

Sorting Windows CMD中文本文件行的Groupby和count

Sorting Windows CMD中文本文件行的Groupby和count,sorting,cmd,grouping,Sorting,Cmd,Grouping,我有一个带有标识符的长文件,例如 A A B C A C 我想执行分组、计数和排序操作,以获取包含以下内容的文件: A 3 C 2 B 1 如何在CMD脚本中实现它?全局编辑-所有代码都已修改,以允许标识符中出现-。标识符不能包含 假设标识符不包含=或$或,并且标识符不区分大小写,下面列出了按标识符排序的计数 @echo off setlocal enableDelayedExpansion :: Clear any existing $ variables for /f "delims=

我有一个带有标识符的长文件,例如

A
A
B
C
A
C
我想执行分组、计数和排序操作,以获取包含以下内容的文件:

A 3
C 2
B 1
如何在CMD脚本中实现它?

全局编辑-所有代码都已修改,以允许标识符中出现
-
。标识符不能包含

假设标识符不包含
=
$
,并且标识符不区分大小写,下面列出了按标识符排序的计数

@echo off
setlocal enableDelayedExpansion

:: Clear any existing $ variables
for /f "delims==" %%V in ('set $ 2^>nul') do set "%%V="

:: Get a count of each identifier
for /f "usebackq delims=" %%A in ("test.txt") do (
  set /a "cnt=!$%%A!+1"
  set "$%%A=!cnt!"
)

:: Write the results to a new file
>output.txt (
  for /f "tokens=1,2 delims=$=" %%A in ('set $') do echo %%A %%B
)

:: Show the result
type output.txt
前缀可以根据需要进行调整。但如果标识符区分大小写,则不能使用此技术

编辑

下面是一个版本,它按递减计数对结果进行排序

@echo off
setlocal enableDelayedExpansion

:: Clear any existing $ variables
for /f "delims==" %%V in ('set $ 2^>nul') do set "%%V="

:: Get a count of each identifier
for /f "usebackq delims=" %%A in ("test.txt") do (
  set /a "cnt=!$%%A!+1"
  set "$%%A=!cnt!"
)

:: Write a temp file with zero padded counts prefixed to the left.
>temp.txt (
  for /f "tokens=1,2 delims=$=" %%A in ('set $') do (
    set "cnt=000000000000%%B"
    echo !cnt:~-12!=%%A=%%B
  )
)

:: Sort and write the results to a new file
>output.txt (
  for /f "tokens=2,3 delims=$=" %%A in ('sort /r temp.txt') do echo %%A %%B
)
del "temp.txt"

:: Show the result
type output.txt

编辑2

这是另一个按计数递减排序的选项,它假定在您的路径中的某个位置

@echo off
setlocal enableDelayedExpansion

:: Clear any existing $ variables
for /f "delims==" %%V in ('set $ 2^>nul') do set "%%V="

:: Get a count of each identifier
for /f "usebackq delims=" %%A in ("test.txt") do (
  set /a "cnt=!$%%A!+1"
  set "$%%A=!cnt!"
)

:: Sort result by count descending and write to output file
set $|repl "\$(.*)=(.*)" "000000000000$2=$1 $2"|repl ".*(.{12}=.*)" $1|sort /r|repl ".{13}(.*)" $1 >output.txt

:: Show the result
type output.txt

您的输出未排序;-)@dbenham,按频率排序。但是,按名称排序也可能很有用。排序顺序似乎是按频率排序的。@Magoo-ooh,我错过了这个解释。您可能是对的。@Magoo-sort order fixed:)看起来非常好!我唯一的问题是,其中一些名称中似乎有一个
-
符号,因此我得到了
缺少的运算符。
错误。@Grzenio-我修改了所有代码以允许标识符中有
-