如何在Bash中检查一个单词是否包含字符串中的所有字母

3
假设我有一个文件,它包含单词(每行一个),还有一个包含字母的字符串。
str = "aeiou"

我想检查文件中有多少个单词包含字符串中的所有字母,它们不必按顺序出现。我首先想到的是使用cat和grep命令。

cat wordfile | grep a | grep e | grep i | grep letters....

这似乎可以正常工作,但我想知道是否有更好的方法。

3个回答

2
如果搜索字符串是固定的,你可以尝试如下操作:
cat wordfile | awk '/a/&&/e/&&/i/&&/o/&&/u/' | wc -l

如果需要,可以使用您喜欢的脚本语言轻松构建搜索模式。由于我更喜欢Python:

str="aeiou"
search=$(python -c 'print "/"+"/&&/".join([c for c in "'"$str"'"])+"/"')
cat wordfile | awk "$search" | wc -l

awk解决方案可能是“最小”的解决方案。祝大家好运! - shellter

2

这里有一个仅使用bash完成的解决方案。请注意,[[ ]] 使其无法在sh中移植。此脚本将读取文件中的每一行,然后测试它是否包含str中的每个字符。要读取的文件必须是脚本的第一个参数。下面的注释描述了操作:

#!/bin/bash

str=aeiou

while read line || test -n "$line"; do    # read every line in file
    match=0;                              # initialize match = true
    for ((i=0; i<${#str}; i++)); do       # for each letter in string
        [[ $line =~ ${str:$i:1} ]] || {   # test it is contained in line - or
            match=1                       # set match false and
            break                         # break - goto next word
        }
    done 
    # if match still true, then all letters in string found in line
    test "$match" -eq 0 && echo "all found in '$line'"; 
done < "$1"

exit 0

测试文件(dat/vowels.txt):

a_even_ice_dough_ball
a_even_ice_ball
someword
notallvowels

输出:

$ bash vowel.sh dat/vowels.txt
all found in 'a_even_ice_dough_ball'

0

虽然有些混乱,但是可以通过打开GNU grep的PCRE-regex标志来一步完成。

 grep -P '^(?=.*a.*)(?=.*e.*)(?=.*i.*)(?=.*o.*)(?=.*u.*)' file | wc -l

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接