linux - 计算字数并指定行数

标签 linux bash

需要根据另一个文件中遇到的单词数(例如,Word1Word2)创建一个文件,并以以下格式指定这些单词出现的行:

Word1: 35 [25, 50, 300, ...]    
Word2: 15 [10, 25, 65, ...]    

最佳答案

不幸的是,您的问题缺少示例输入文件来演示您需要处理的各种事情以及基于它们的预期输出,所以我只是编造一些东西。

给定文件

wordlist.txt:

cat
dog
fish
horse

input.txt:

There are three fish.
Two red fish.
One blue fish and a brown dog.
There are no matching words on this line.
Also there is no cat, only the dog. Oh, there is a white dog too.
There are doggies.

这个 perl 脚本将打印匹配的单词及其行,包括每行一个单词的多个匹配:

#!/usr/bin/env perl
use warnings;
use strict;
use autodie;
use feature qw/say/;
use English;

my %words;

open my $wordlist, "<", $ARGV[0];
while (<$wordlist>) {
    chomp;
    $words{$_} = [];
}

open my $text, "<", $ARGV[1];
while (<$text>) {
    while (my ($word, $positions) = each %words) {
        while (m/\b\Q$word\E\b/g) { # Match all occurrences of the word by itself
            push @$positions, $NR;
        }
    }
}

$OFS = ' ';
for my $word (sort keys %words) {
    my $positions = $words{$word};
    say "$word:", scalar(@$positions), join(',', @$positions);
}

示例:

$ perl words.pl wordlist.txt input.txt
cat: 1 5
dog: 3 3,5,5
fish: 3 1,2,3
horse: 0

关于linux - 计算字数并指定行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57256979/

相关文章:

command-line - 找不到 NGINX brew install 命令

linux - 如何将字符串添加到二进制操作然后将其保存到 bash 中的 .dat 文件

python - Cron 作业生成 crontab.txt : not found

在C linux中创建子进程

java - tr Locale、Windows 7 和 Linux 中的日期格式给出 2 个结果

java.lang.NoSuchFieldError : DEF_CONTENT_CHARSET from linux terminal with twilio 错误

bash - 使用 Control C 防止 shell 脚本退出

linux - bash 行继续中断

c++ - 使用 C++ 标准库在 Linux 上编译

c - Winsock2.h 似乎从 mingw 中丢失?