1

I am trying to check if the string is in format in shell script. below is the code i am trying and the output i want to get.

Format: <datatype>(length,length) | <datatype>(length,length)

I have multiple cases with this scenario, if both datatypes have () then it should show pass, else fail.

Eg. decimal(1,0)|number(11,0) this should pass but int|number(11,0) or decimal(1,0)|int should fail.

Code1:

INPUT='decimal(1,0)|number(11,0)'
sub="[A-Z][a-z]['!@#$ %^&*()_+'][0-9][|][A-Z][a-z]['!@#$ %^&*()_+'][0-9][|]"
if [ "$INPUT" == "$sub" ]; then
    echo "Passed"
else
    echo "No"
fi

Code 2:

INPUT='decimal(1,0)|number(11,0)'
sub="decimal"
if [ "$INPUT" == *"("*") |"*"("*") " ]; then
    echo "Passed"
else
    echo "No"
fi

Any help will be fine. Also note, I am very new to shell scripting.

7
  • You want =~, not ==, for a regular expression operation. = is a glob. And if you do want a glob, you can't quote the right-hand side -- it should be [[ $INPUT = $sub ]] -- note [[ instead of [; [ only supports exact comparisons (and only in [[ are unquoted expansions safe). Commented Apr 26, 2022 at 15:07
  • The above is only true in shells like bash with ksh extensions; /bin/sh doesn't support [[ at all, nor does it have any kind of built-in regex support, though you can evaluate globs there using case. Commented Apr 26, 2022 at 15:08
  • Thanks for the quick response and information . But i require the sub string which i can use in the if condition and add the other code i wan to impelement. Commented Apr 26, 2022 at 15:16
  • You can nest case inside of if. Baseline POSIX-standard /bin/sh simply doesn't support any substring operation without case; you need an extended shell (ksh, bash, zsh, etc) for that to be built-in. Commented Apr 26, 2022 at 16:31
  • 1
    Also, note that [ isn't guaranteed to support == at all. The only standard-defined string comparison operator is =. Commented Apr 26, 2022 at 16:35

2 Answers 2

2
+100

Reading both values into variables, first removing alpha characters and then checking variables are not empty

result='FAIL'
input='int|number(6,10)'

IFS="|" read val1 val2 <<<"$(tr -d '[:alpha:]' <<<"$input")"

if [ -n "$val1" ] && [ -n "$val2" ]; then
    result='PASS'
fi
echo "$result: val1='$val1' val2='$val2'" 

Result:

FAIL: val1='' val2='(6,10)'

For input='decimal(8,9)|number(6,10)'

PASS: val1='(8,9)' val2='(6,10)'
Sign up to request clarification or add additional context in comments.

Comments

2

That looks like just a simple regex to write.

INPUT='decimal(1,0)|number(11,0)'
if printf "%s" "$INPUT" | grep -qEx '[a-z]+\([0-9]+,[0-9]+\)(\|[a-z]+\([0-9]+,[0-9]+\))*'; then
    echo "Passed"
else
    echo "No"
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.