在Windows Batch和Bash中按单词读取文件

时间:2013-01-22 18:58:44

标签: windows bash cmd

我需要打印文件中每个单词重复次数的所有单词。但我无法理解如何在Win CMD和Bash中按单词读取文件。我该怎么办?

1 个答案:

答案 0 :(得分:1)

仅限Windows批处理

这将枚举文件中的每个单词并显示单词及其计数。

<强>限制

  1. 8191的批次行长度限制(Windows XP +)。对于较旧的操作系统2047
  2. <强>脚本

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    for /f "delims=" %%A in (file.txt) do (
        set "_=%%A"
        call :Expand_
    )
    
    :: Display the Word and Count
    rem set word:
    for /f "tokens=2,3 delims=:=" %%X in ('set word:') do echo %%X = %%Y
    goto End
    
    
    :Expand_
    :: Clean Special Characters
    set "_=%_:"=%"
    set "_=%_:^=%"
    set "_=%_:<=%"
    set "_=%_:>=%"
    set "_=%_:&=%"
    set "_=%_:|=%"
    :: Replace Whitespace
    set "_=%_:  =%"
    :: Remove Plurals
    rem set "_=%_:'s=%"
    :: Clean Punctuation
    :WordLoop
    for /f "tokens=1,* delims=`~!@#$%%*()-_+=\[]{};:/?., " %%X in ("%_%") do (
        set ".=%%X"
        call :Expand.
        set "_=%%Y"
    )
    if defined _ goto WordLoop
    goto :eof
    
    :Expand.
    :: Count the Words
    if defined word:%.% (
        set /a "word:%.%+=1"
    ) else (
        set "word:%.%=1"
    )
    goto :eof
    
    
    :End
    endlocal