我正在尝试匹配给定字符串的所有字符,但这些字符应按照bash脚本给出的顺序进行匹配。
while [[ $# -gt 0 ]]; do
case $1 in
-i)
arg=$2
egrep "*[$arg]*" words.txt
shift ;;
esac
shift
done
$ sh match_the_pattern.sh -i aei words.txt
应返回类似
的字词abstentious
adventitious
sacrilegiousness
如果您注意到,首先匹配a
,然后匹配e
,然后匹配i
,它们都是按顺序排列的。另外,整个单词都经过匹配和过滤。
答案 0 :(得分:3)
您可以使用getopts
和一些bash参数替换来构造查询字符串。
#!/bin/bash
while getopts 'i:' choice
do
case "${choice}" in
i)
length=${#OPTARG}
for((count=0;count<length;count++))
do
if [ $count -eq 0 ]
then
pattern="${pattern}.*${OPTARG:count:1}.*"
else
pattern="${pattern}${OPTARG:count:1}.*"
fi
done
;;
esac
done
# The remaining parameter should be our filename
shift $(($OPTIND - 1))
filename="$1"
# Some error checking based on the parsed values
# Ideally user input should not be trusted, so a security check should
# also be done,omitting that for brevity.
if [ -z "$pattern" ] || [ -z "$filename" ]
then
echo "-i is must. Also, filename cannot be empty"
echo "Run the script like ./scriptname -i 'value' -- filename"
else
grep -i "${pattern}" "$filename"
fi
答案 1 :(得分:2)
更改此:
arg=$2
egrep "*[$arg]*" words.txt
对此:
arg=$(sed 's/./.*[&]/g' <<< "$2")
grep "$arg" words.txt
如果这还不是您所需要的,请编辑您的问题以阐明您的要求,并提供更真实的示例输入/输出。
答案 2 :(得分:1)
您的正则表达式匹配'a'或'e'或'i',因为它们在字符集中([]
)。
我认为您正在寻找的正则表达式是
a+.*e+.*i+.*
匹配一次或多次“ a”,然后匹配任何内容,然后匹配“ e”一次或多次,然后匹配所有内容,然后匹配“ i”一次或多次。