• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 497
  • Last Modified:

How to find a value from a variable string in korn shell script

I am writing a ksh script and the above solutions as mentioned in the my previous question How to parse a string in unix and get a value
 are not working for dynamic value search. I have modified the question to suit my requirement.

I have a string as below

MON_DT ="BD0 $DATE_BD0|BD1 $DATE_BD1|BD2 $DATE_BD2|BD3 $DATE_BD3|BD4 $DATE_BD4|BD5 $DATE_BD5"MON_DT

search string
CHK_DT='jun 25 2013'

Values of the Variables are like this.

DATE_BD0 = "apr 1 2014"
DATE_BD1 = "mar 31 2103"
DATE_BD2 = "Feb 3 2012"
DATE_BD3 = "Jan 22 2013"
DATE_BD4 = "may 21 2013"
DATE_BD5 = "jun 25 2013"
DATE_BD6 = "jul 27 2013"

Now I need to search $CHK_DT form the $MON_DT string and get the value BD5.
as mentioned in the example, As matter $CHK_DT dynamically changes we need to get the appropriate BD values accordingly.

As in the I want the Result as BD5.

Can some one Answer this query, this is very urgent for me. Thanks in advance.
0
welcome 123
Asked:
welcome 123
2 Solutions
 
woolmilkporcCommented:
My first solution presented in the other Q needs just small modifications to work with the new data:

echo $MON_DT | awk -v S="$CHK_DT" -F'|' '{for(n=1;n<=NF;n++) if($n~S) print substr($n,1,index($n," "))}'

Or, if your shell supports it:

awk -v S="$CHK_DT" -F'|' '{for(n=1;n<=NF;n++) if($n~S) print substr($n,1,index($n," "))}' <<< $MON_DT

Please note the double quotes around "$CHK_DT" and the modified "print" part.
0
 
simon3270Commented:
Assuming that you have set $MON_DT, and the date you are looking for is in $CHK_DT, then this will get the matching tag in $MATCH_TAG:
MATCH_TAG=
OIFS=$IFS
IFS='|'
for ent in $MON_DT; do
  IFS=$OIFS
  ent_tag=`echo $ent | sed 's/ .*//'`
  ent_val=`echo $ent | sed 's/^[^ ]* //'`
  if [ "$ent_val" = "$CHK_DT" ]; then
    MATCH_TAG="$ent_tag"
    break
  fi
done
IFS=$OIFS

Open in new window

If it doesn't find the date, $MATCH_TAG will be empty.

note that the date must match exactly (be the same case).  if the match should not be case sensitive, let me know and I'll add that.

(edit to correct typo in $CHK_DT)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now