I have written the following bash function prArgv
Suppose the calling sequence is as follows
prArgv VAL1 VAL2 DESC VAL3 VAL4 v2d1 s4 p15
The call will look at the tag k1v2, add the numbers together, in this case 2+1=3
This means that the function will look at the first 3 user arguments only (VAL1 VAL2 DESC).
The s4 tag is a shift tag, so that when I print VAL1 VAL2 DESC, everything is shifted by 4 characters
to the right.
Thus
1234VAL1 VAL2 DESC # print statement shifted by 4 characters to the right.
The thing I am trying to do is that if the user puts the p-tag, the description which is the
last user argument defined ($3), is printed at the position defined by the corresponding number.
For example, p15 will place DESC starting from the 15 character position.
prArgv() {
frmt_v2d1="${bGn}%s %s${nWh} %s${nColor}\n"
#=============================================================================
# Set location of format tag and the shift
lastArgv="$#" # lastArgv =
# Position of last argument equals the number of arguments
frmtPos=`expr $lastArgv - 1` # frmtPos =
# Position of argument before last
shiftpos=$lastArgv
#=============================================================================
# Construct variable names from where to capture the required format
# Construct shift format variable, 's' followed by amount of shift
frmtShift="${!shiftpos}" # frmtShift = "s2"
# Construct arguments format variable for colored output
frmtArgv="frmt_${!frmtPos}"
#=============================================================================
# Construct print format
# Shift tag detected
if [[ "${!shiftpos}" =~ ^s[0-9]+$ ]] ; then
frmt="${!frmtShift}${!frmtArgv}"
# Position tag detected
elif [[ "${!shiftpos}" =~ ^p[0-9]+$ ]] ; then
frmt="${!frmtShift}${!frmtArgv}"
# No shift or position tags detected
else
frmt="${!frmtArgv}"
fi
echo "frmt = $frmt"
#=============================================================================
# Compute number of arguments to print. This is done by adding the numbers
# in the format tag together.
sepString=`echo "${!frmtPos}" | sed 's/\([0-9][0-9.]*\)/ & /g'`
strArr=( $sepString )
# Add the numeric fields together
n=0
for str in "${strArr[@]}"; do
if [[ "$str" =~ ^[0-9]+$ ]]; then
n=$((n+str))
fi
done
#=============================================================================
# Compute the total length of all user arguments excluding the description
m=$((n-1))
strArr=( ${@:1:$m} )
echo "str = ${@:1:$m}"
totlLen=0
for str in "${strArr[@]}"; do
lenArgv=${#str}
totlLen=$((totlLen+lenArgv))
done
echo "totlLen = $totlLen"
# str=${!n}
# strLen=${#str}
# echo "str, strLen = $str, $strLen"
printf "$frmt" "${@:1:$n}" # print command
}