Matthew Cordaro
Matthew Cordaro

Reputation: 757

Check and modify format of variable in expect script

I am trying to verify that the format of a variable is a number and is at least 10 digits long with leading zeros, inside of an expect script.

In a bash script it would look something like this:

[[ "$var" != +([0-9]) ]] && echo "bad input" && exit
while [[ $(echo -n ${var} | wc -c) -lt 10 ]] ; do var="0${var}" ; done

For the following input:

16

I am trying to achieve the following output:

0000000016

Upvotes: 1

Views: 2752

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

The simplest way to check whether a variable has just digits is to use a regular expression. Expect's regular expressions are entirely up to the task:

if {![regexp {^\d+$} $var]} {
    puts "bad input"
    exit
}

Padding with zeroes is best done by formatting the value; if you know C's printf(), you'll recognize the format:

set var [format "%010d" $var]

Upvotes: 2

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Expect is actually just an extension of TCL, so you can use any facility that TCL provides. TCL is an unusual language, but it's not hard to do what you want.

# Set a test string.
set testvar 1234567890

# Store the match (if any) in matchvar.
regexp {\d{10,}} $testvar matchvar
puts $matchvar

# Test that matchvar holds an integer.
string is integer $matchvar

The string is command is relatively new, so you might have to rely on the return value of regexp if your TCL interpreter doesn't support it.

Upvotes: 0

Related Questions