Saturday, June 4, 2022

[SOLVED] Checking if the string is in proper format in Shell Scripting

Issue

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.


Solution

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)'


Answered By - LMC
Answer Checked By - Cary Denson (WPSolving Admin)