Check whether there is only numbers

Hi everyone,

I must make a script which will be executed as follows :

./script.sh Directory/n[0-9].car where there can be as many numbers as we may want.

I'd like to : - ignore the Directory ; Meaning I just need n[0-9].car
- Check the name of the file : has it got some Alphabetic Characters after the n? in which case it's not a proper file name.
- *Extract* the number in the name, to be able to compare it to something else after.

Thanks in advance,

~ Lyth_o ~

At least an idea to work with:

FILE=$( basename $1 )
CORE=$( echo $FILE | sed '/s/^n//' | sed 's/$\.car//' )
TEST=$( echo $CORE | egrep -o '[[:alpha:]]' )
if [ -n "$TEST" ]
then
  echo "File name not valid!"
fi

Ok thank you.
I'll try to understand sed's use. (I have never understood what it does or how to use it...)
^^

Presuming you do not literally mean ./script.sh Directory/n[0-9].car which is a globbing expression which may expand to multiple files as input, but that you mean a single file that consists of an n followed by multiple digits (n>=1) followed by the extension .car:

If so, you could try this alternative which uses no external programs:

no_n="${1##*/n}"
nr="${no_n%.car}"
case $nr in
  *[^0-9]*) echo "File name ${1##*/} invalid.."
esac

Here is another way - remove digits from the basename of the file spec and you get "n.car" for good files.


if [[  $(basename $filename | tr -d '[:digit:]') = "n.car" ]] ; then
   echo "$filename is ok"
else
   echo "$filename is not ok"
fi

Bash/ksh:

if [[ ! ${1//[0-9]} =~ .*/?n.car ]]; then
  echo "File name ${1##*/} invalid.."
fi

Thank you everyone.

I took Scrutinizer's first option.

Does your second option do the same?

Do you know how to get the last character of a line?

I have the code :

echo `$1 $2`

And I would like to compare the last character of the result (which is a number) with a certain number...

Edit : I have found something working...

But, does someone know how to echo something when executing `$1 $2` ($1 is ./program and $2 an argument of it) provokes an error?

Hi,

The second option does the same but is not posix compliant. If a script is posix compliant it will work with most shells. The second option uses more advanced options that are available in ksh93 and bash.

To get the last character of string b:

echo ${b#${b%?}}