linux - How to "grep" in array with dot "." precisely? -
i'm trying check if user input $1 exist in array. , here code:
array=( aaa.bbb.ccc ccc.ddd.aaa ) echo ${array[@]} | grep -o -w "$1"
what expect "aaa.bbb.ccc" or "ccc.ddd.aaa" can found. however, in case, "aaa" or "ccc" can pass validation. seems dot not treated part of string.
should use regex or other grep option?
it sounds want:
- literal string matching
- against entire input lines.
therefore, use -f
(for literal matching) , -x
whole-line matching:
array=( aaa.bbb.ccc ccc.ddd.aaa ) printf '%s\n' "${array[@]}" | grep -fx "$1"
now, literal strings aaa.bbb.ccc
, ccc.ddd.aaa
match, not substrings such aaa
.
since you're matching entire line, use of -o
(to output matching part of each line) unnecessary.
also note how printf '%s\n' "${array[@]}"
must used print each array element on own line, whereas echo ${array[@]}
prints elements on single line (with whitespace normalization due word-splitting , potential globbing applied, because ${array[@]}
not enclosed in "..."
).
the problem approach:
grep
defaults (basic) regular expressions,$1
value containing.
result in.
being interpreted mean "any single character".echo ${array[@]}
problematic due potentially unwanted whitespace normalization , globbing, stated;echo "${array[@]}" | grep -fwo "$1"
improvement, bears slight risk of false positives.
Comments
Post a Comment