How do I do an exact word match on a variable in ksh?

拈花ヽ惹草 提交于 2019-12-23 23:03:09

问题


I used the following syntax as part of a ksh script to verify if the word Validation exists in LINE_FROM_FILE.

[[ "${LINE_FROM_FILE##*Validation}" != "${LINE_FROM_FILE}" ]] && print "match Validation"

The problem of this syntax is that it is also matching words like Valid or ValidationVALID etc. and my goal is to exactly match the word Validation in the variable $LINE_FROM_FILE.

I ask if it is also possible to use Perl syntax in my script to exactly match the word Validation, for example:

[[ ` some perl command ` = Validation  ]] && print "match Validation"

回答1:


Test whether the line contains the word between word-separating characters. A helpful trick is to add a word-separating character at the beginning and at the end of the string, in case the word is at the beginning or end of the string.

[[ " $LINE_FROM_FILE " == *[![:alnum:]]Validation[![:alnum:]]* ]]

This assumes that words consist of letters and digits only. Adjust the pattern if you have a different definition.

Note that the test you wrote, [[ "${LINE_FROM_FILE##*Validation}" != "${LINE_FROM_FILE}" ]], is a complicated way of writing [[ $LINE_FROM_FILE = *Validation* ]] (i.e., checking for Validation as a substring).




回答2:


if your using bash, you're in luck:

bash regexs

Example:

input=$1


if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
#                 ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
# NNN-NN-NNNN (where each N is a digit).
then
  echo "Social Security number."
  # Process SSN.
else
  echo "Not a Social Security number!"
  # Or, ask for corrected input.
fi


来源:https://stackoverflow.com/questions/3565283/how-do-i-do-an-exact-word-match-on-a-variable-in-ksh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!