给出如下的字符串:
one/two one/three two/four five/six seven我用这个正则表达式:
(?<=\s)([^\/]*)(?=\/|\s)(?!.*\1\b)
得到:
one
two
five
seven这就是我想要的结果。所有唯一的“根”字符串。它在[医]风疹中工作,但是bash不返回任何匹配。
我知道我使用的regex包含一个感叹号,这会使bash感到困惑,但是在它前面添加一个斜杠转义字符是没有帮助的,它周围的单引号也没有帮助。
我用在bash里,就像这样:
[[ $string =~ (?<=\s)([^\/]*)(?=\/|\s)(?!.*\1\b) ]] echo ${BASH_REMATCH}我不能为regex使用双引号,因为我使用的bash版本将双引号中的内容解释为文字字符串。
我怎么能让bash理解这个正则表达式?
发布于 2013-09-25 00:10:56
Bash绝对不理解与perl兼容的正则表达式。我只想说一些粗俗的习语:
string="one/two one/three two/four five/six seven"
roots=$(sed 's/\/[^[:blank:]]*//g' <<< "$string" | tr ' ' '\n' | sort -u)
echo "$roots"或
roots=() # empty array
for word in $string # no quotes to obtain word splitting
do
roots+=( ${word%/*} ) # add to the array the bit before the last slash
done
printf "%s\n" "${roots[@]}" | sort -u或者,使用bash 4,使用关联数组来模拟集合的行为。
declare -A roots # an associative array
for word in $string # no quotes to obtain word splitting
do
roots[${word%/*}]=1
done
printf "%s\n" "${!roots[@]}" # print out the hash keyshttps://stackoverflow.com/questions/18993535
复制相似问题