user2836003
user2836003

Reputation:

Creating loop within Unix Script

I'm curious of how I might go about creating a more detailed output within the same scripting file. I would like to modify the script so that after it finds the matching line for the currency code, it outputs the following:

Currency code: {currency code value}     
Currency name: {currency name value}   
Units per USD: {units value}
USD per unit : {USD value}  

What I have so far:

#!/bin/bash

# Set local variable $cc to first command line argument, if present
cc=$1
# execute the do loop while $curr is blank
while [ -z "$curr" ]
do
# test if $cc is blank.  If so, prompt for a value
    if [ -z "$cc" ]
    then
        echo -n "Enter a currency code: "
        read cc
    fi
    # Search for $cc as a code in the curr.tab file
    curr=`grep "^$cc" curr.tab`
    # clear cc in case grep found no match and the loop should be repeated
    cc=
done
# echo the result
echo $curr

The curr.tab I am using would look something like this:

USD US Dollar          1.0000000000 1.0000000000
EUR Euro               0.7255238463 1.3783144484
GBP British Pound      0.6182980743 1.6173428992
INR Indian Rupee      61.5600229886 0.0162443084
AUD Australian Dollar  1.0381120551 0.9632871472
CAD Canadian Dollar    1.0378792155 0.9635032527
AED Emirati Dirham     3.6730001428 0.2722570000
MYR Malaysian Ringgit  3.1596464286 0.3164911083

Upvotes: 0

Views: 117

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

At the end, instead of echo $curr do:

[[ $curr =~ ^(...)[[:space:]]+(.+)([[:space:]]+([[:digit:]\.]+)){2}$ ]]
printf "Currency code: %s\nCurrency name: %s\nUnits per USD: %s\nUSD per unit : %s\n" "${BASH_REMATCH[@]:1}"

Upvotes: 2

Related Questions