Operating System - Linux
1753856 Members
7395 Online
108809 Solutions
New Discussion юеВ

Re: Problem with string Comparison

 
SOLVED
Go to solution
mougli
Occasional Advisor

Problem with string Comparison

Hi,

Sorry for such a basic question. But still don't seem to get this working.

I get a fiename as an argument to the script and based on the file name, I need to rename it with the date appended to it.

#!/bin/ksh

INFILE=$1
echo "The incoming filename is $INFILE"
DAYSTRING=`date +%Y%m%d`
TIMESTRING=`date +%H%M%S`
if [ "$INFILE" = "prod_h_datafile_???.txt" ]
then
echo "Match Found"
OUTFILE=${DAYSTRING}${TIMESTRING}_hvendr.sig
fi
echo "The outgoing filename is $OUTFILE"

The script seeems to be working fine if I remove the ??? from the if statement and add the actual number. But with the ???, the comparison always fails.

Please suggest.

TIA
12 REPLIES 12
Jonathan Fife
Honored Contributor
Solution

Re: Problem with string Comparison

ksh doesn't do regexp on strings like that.

If you do something like

if [ $(echo $INFILE | egrep -c "prod_h_datafile_???.txt") -gt 0 ]

then it should work.
Decay is inherent in all compounded things. Strive on with diligence
Jonathan Fife
Honored Contributor

Re: Problem with string Comparison

actually that doesn't work...
Decay is inherent in all compounded things. Strive on with diligence
Jonathan Fife
Honored Contributor

Re: Problem with string Comparison

egrep -c "prod_h_datafile...\.txt"

there we go :)
Decay is inherent in all compounded things. Strive on with diligence
mougli
Occasional Advisor

Re: Problem with string Comparison

Thanks!! It worked..
mougli
Occasional Advisor

Re: Problem with string Comparison

Sorry. I think there is a problem with your answer. Now If I add similar comparison statements, it returns 0 for all of them and all the comparison are true..
harry d brown jr
Honored Contributor

Re: Problem with string Comparison

Try

if [ `echo ${INFILE} | grep "prod_h_datafile_[0-9]\{8\}\.txt$"` ]

live free or die
harry d brown jr
Live Free or Die
James R. Ferguson
Acclaimed Contributor

Re: Problem with string Comparison

Hi:

Instead of using a regular expression with an 'if' use a 'case':

James R. Ferguson
Acclaimed Contributor

Re: Problem with string Comparison

Hi:

Sorry, I clicked the wrong button!

Instead of using a regular expression with an 'if' use a 'case' statement. Thry this version of your script:

#!/usr/bin/ksh
INFILE=$1
echo "The incoming filename is $INFILE"
DAYSTRING=`date +%Y%m%d`
TIMESTRING=`date +%H%M%S`
case $INFILE in
prod_h_datafile_[0-9][0-9][0-9].txt )
echo "Match Found"
OUTFILE=${DAYSTRING}${TIMESTRING}_hvendr.sig
;;
* )
echo "NO match!"
;;
esac
echo "The outgoing filename is $OUTFILE"

...

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Problem with string Comparison

To do pattern matching in sh/ksh you need to use [[ ]]:
if [[ "$INFILE" = prod_h_datafile_???.txt ]]

Note you can't quote the pattern.