附加到Bash关联数组中的元素

时间:2015-02-26 21:32:03

标签: arrays csv

我的名字是迈克,我是Bash编程的总菜鸟。话虽如此,请不要咀嚼纸浆。这是我的情景。我正在导入一个csv并逐行处理它。它在AD和管道中查找导致变量$ ADresult1的信息。

然后我接受输出并将其发送到数组中。

declare -A arrmail
arrmail[$ADresult1]="$v1, $v3"
appendvar+="; ${arrmail[$ADresult1]}"
if [ ! -z "${arrmail[$ADresult1]}" ]; then
    echo ${arrmail[@]}
else
    echo ${arrmail[@]}="$appendvar"
fi

现在在我的CSV文件中,var $ADresult1有多个相同的条目,但每个元素应该不同。

例如:第一行可能包含arrmail[p100]=Y2K, Y2J 第二行可能是arrmail[p100]=GGG, GG1

我的问题是如何将第一行和第二行的元素组合成一行输出和/或如果可能的话。

例如arrmail[p100]=Y2K, Y2J; GGG, GG1

如果需要,我可以发布整个脚本以获得更大的图片。

这是剧本。

#!/bin/bash

###--------------------------------------------------------------------------
# Author : Volha Zhdanava (p146819)
# Date   : 11-FEB-2013
# Purpose: To automate the process of sending out notification emails to developers when 
# Assigned DEV Machine is on the Expired Devices List.
#----------------------------------------------------------------------------
#            ----MODIFIED----
#----------------------------------------------------------------------------------------------------
#  Author               Revsn Date      Revsn ID        Revsn Purpose
# Mike Bell         02-28-14    Rev.03      Add ability to email j or p number
# Mike Bell     01-02-15    Rev.04      Add verbiage about 90 day licensing
###----------------------------------------------------------------------------------------------------


Purple='\e[1;35m'
ColorOFF='\e[0m'
TO_TEAM="dev-tools@edwardjones.com"

#-----------------------------------------
#Ask for input CSV file
#-----------------------------------------

FILEDIR="/export/share/is/dev_env/expdev"
FILENAME="expired_devices.csv"

#if the directory is not empty, find the csv file
if [[ $(ls -A $FILEDIR) ]]
then
#check if the csv file was stored with default name <expired_devices.csv>

       if [ -f $FILEDIR/$FILENAME ]
      then
#absolute path to the downloaded file
       CSVFILE=`echo $FILEDIR/$FILENAME`
#if the csv file was stored under a user-defined name,
#re-define the absolute path to that file

      else  
             #count how many files are saved in the expdev directory
             NAME=( `ls -A $FILEDIR` )
             CNT=${#NAME[@]}
             echo -e "There is/are ${Purple}${CNT}${ColorOFF} file(s) in the ${Purple}$FILEDIR${ColorOFF} directory:"
         echo ${NAME[@]}
        #if there is only one file saved within the expdev directory
                if [ ${CNT} -eq 1 ]
                   then
                     FILENAME=${NAME[0]}          
                   else
        #it will prompt to enter the name of the file
                 REPLY="n"
                 while [ "$REPLY" != "y" ]  
                 do
                  echo -e "Please enter the full name of the downloaded csv file: \c"
                  read FILENAME
                  echo -e "You entered ${Purple}$FILENAME${ColorOFF}. Is this correct? y/n: \c\n"
                  read ANSWER 
                  REPLY=`echo $ANSWER | tr [:upper:] [:lower:]`
                 done
                 fi
              #verify the specified file exists in <expdev> directory 

              echo `ls -Al $FILEDIR/$FILENAME` 
              echo -e "\nThe script will run against the listed above ${Purple}$FILENAME${ColorOFF} file.\n${Purple}NOTE${ColorOFF}: Do NOT proceed if it says ${Purple}No such file or directory${ColorOFF}.\nWould you like to proceed? y/n -->:\c "
                 read PROCEED
                 PROCEED=`echo $PROCEED | tr [:upper:] [:lower:]`
                     if [ "$PROCEED" == "y" ]
                           #user agrees
                       then
                        CSVFILE=`echo $FILEDIR/$FILENAME`
                       else
                        echo -e "Make sure you saved your CSV file in ${Purple}$FILEDIR${ColorOFF} directory and run the script again."
                        exit 1
                     fi

        fi
#----------------------------------------------
#Remove header from CSVFILE
#and create a temp csvfile.txt 
#for "WHILE READ" loop
#----------------------------------------------
Nrows=`cat ${CSVFILE}| wc -l`
N=`expr $Nrows - 1`
tail -$N ${CSVFILE} > csvfile.txt
#----------------------------------------------
#Determine the Extension Date
#----------------------------------------------
TODAYsDATE=`date +"%a"`
case $TODAYsDATE in
Mon ) ExtDate=`date --date='4 day' +"%A, %d-%b-%Y"`
    ;;
Tue ) ExtDate=`date --date='6 day' +"%A, %d-%b-%Y"`
    ;;
Wed ) ExtDate=`date --date='6 day' +"%A, %d-%b-%Y"`
    ;;
Thu ) ExtDate=`date --date='6 day' +"%A, %d-%b-%Y"`
    ;;
Fri ) ExtDate=`date --date='6 day' +"%A, %d-%b-%Y"`
    ;;
* ) echo "Cannot determine the Extention Date."
    REPLY="n"
    while [ "$REPLY" != "y" ]
    do
    echo -e "Please enter Extended Date: \c"
    read ExtDate
    echo -e "You entered ${Purple}$ExtDate${ColorOFF}. Is this correct? y/n: \c "
    read ANSWER
    REPLY=`echo $ANSWER | tr [:upper:] [:lower:]`
    done

esac

echo -e "The Extended Date for the Application Owners will be ${Purple}$ExtDate${ColorOFF}.\nPlease make a note for End Date in the APEX Workstation Tracking Tool." 

#create a temp confirmation file that will be sent to dev-tools
echo -e "\nThe Extended Date is $ExtDate.\nSent emails to: " > confirmation.txt

#----------------------------------------------
#Read the csvfile.txt
#----------------------------------------------
while IFS=','  read v1 v2 v3 v4 other
do

#----------------------------------------------
#Determine email address
#----------------------------------------------
v2=` echo $v2 | tr '"/,\&' ' ' `
NAME=( ${v2} )
cnt=${#NAME[@]}
#-----------------------------------------------
# Filter j or p<number> userids from table V2
#--------------------------------------------------

if [[ "$NAME" =~ [P|p][[:digit:]]{6}$|[J|j][[:digit:]]{5}$ ]]

    then
        ADresult1=`getent passwd "$NAME" | awk -F":" '{print $1}'`
echo ${ADresult1}

#------------------------------------------------------------------------------------------------------
# Processing Array
#-----------------------------------------------------------------------------------------------------

declare -A arrmail

arrmail[$ADresult1]="$v1, $v3"

appendvar+="; ${arrmail[$ADresult1]}"

if [ ! -z "${arrmail[$ADresult1]}" ]

        then
               echo ${arrmail[@]}
else

        echo ${arrmail[@]}="$appendvar"
fi

#--------------------------------------------------------------------------------------
# If query matches j or p#, then email user
#------------------------------------------------------------------------------------------
#
#
#           v1=` echo $v1 | tr '"' ' ' `
#                        SUBJECT=" ${v1}, ${v3} - Your Development Machine Status Update"
#
#                        TO="${ADresult1}@edwardjones.com"
#
#                        v4=` echo $v4 | tr '"' ' ' `
#
#           devmailmessage="\nGreetings ${NAME[0]}, \n\nI am in the process of cleaning up the machines in our lab.\n\nAssigned device: ${v1} \n\nEffort: ${v3}\n\nThe above machine have been assigned to you since ${v4}.\n\nDo you still need this machine or can I reclaim it?\nIf this machine is still required, please let us know how much longer you will need it.\nPlease keep in mind that Dev. workstations or laptops can only be assigned for 90 days due to licensing restrictions.\n\nIf this machine is no longer needed, please let us know also.\n\nThis machine will be rebuilt on or after $ExtDate.\n\nPlease reply to dev-tools@edwardjones.com by $ExtDate.\n\n\nThank you,\n\nDevelopment Environment Support team\ndev-tools@edwardjones.com " 
#
#echo -e ${devmailmessage}|mail -s "$SUBJECT" $TO -- -f $TO_TEAM

#--------------------------------------------------------------------------------------------
# If query does not match j or p number, then lookup username via first and last name
#----------------------------------------------------------------------------------------------

elif [ ${cnt} -eq 2 ]

    then

        ADresult=`getent passwd | grep -i "${NAME[0]}" | grep -i "${NAME[1]}"`

echo ${ADresult}
#count search results from Active Directory; only email if there is one unique result
        ADsearch1=`echo ${ADresult} | grep -i "${NAME[0]}" | wc -l`
        ADsearch2=`echo ${ADresult} | grep -i "${NAME[1]}" | wc -l`
                if [ ${ADsearch1} -eq 1 ] && [ ${ADsearch2} -eq 1 ]
                   then
                        pNumber=`echo ${ADresult} | awk -F":" '{print $1}'`
#------------------------------------------------------------------------------------------------------
# Processing Array
#-----------------------------------------------------------------------------------------------------

#declare -A arrmail

#arrmail[$pNumber]="$v1, $v3"

#appendvar+="; ${arrmail[$pNumber]}"

#if [ ! -z "${arrmail[$pNumber]}" ]

#        then
#           {arrmail[$pNumber]}="${arrmail[$ADresult1]}"
#else

#   {arrmail[$ADresult1]}="$appendvar"
#fi

#------------------------------------------------------------------------------------------------------------
#                        v1=` echo $v1 | tr '"' ' ' `
 #                       SUBJECT=" ${v1}, ${v3} - Your Development Machine Status Update"

  #                      TO="${pNumber}@edwardjones.com"

   #                     v4=` echo $v4 | tr '"' ' ' `

#           devmailmessage="\nGreetings ${NAME[0]}, \n\nI am in the process of cleaning up the machines in our lab.\n\nAssigned device: ${v1} \n\nEffort: ${v3}\n\nThe above machine have been assigned to you since ${v4}.\n\nDo you still need this machine or can I reclaim it?\nIf this machine is still required, please let us know how much longer you will need it.\nPlease keep in mind that Dev. workstations or laptops can only be assigned for 90 days due to licensing restrictions.\n\nIf this machine is no longer needed, please let us know also.\n\nThis machine will be rebuilt on or after $ExtDate.\n\nPlease reply to dev-tools@edwardjones.com by $ExtDate.\n\n\nThank you,\n\nDevelopment Environment Support team\ndev-tools@edwardjones.com "

 #                       echo -e ${devmailmessage}| mail -s "$SUBJECT" $TO -- -f $TO_TEAM
#       else
 #                           TO=`echo "ACTION REQUIRED: Email address cannot be determined for the following user: ${v2}, with assigned device: ${v1}. Please email this user yourself."`
               fi

#            else
 #                          TO=`echo "ACTION REQUIRED: Email address cannot be determined for the following user: ${v2}, with assigned device: ${v1}. Please email this user yourself."`

    fi
#echo -e "\n$TO ${v2}, ${v1}" >> confirmation.txt
echo "NEXT ROW"

done < csvfile.txt

#----------------------------------------------
#sending out confirmation email to dev-tools
#----------------------------------------------
#subject="WW - Notification Emails to Developers - Status"
#cat confirmation.txt |  mail -s "$subject" $TO_TEAM -- -f $TO_TEAM

#echo -e "Result: Processing is COMPLETED. Please check the ${Purple}$subject${ColorOFF} email. Note: ${Purple}$FILENAME${ColorOFF} file was deleted from ${Purple}$FILEDIR${ColorOFF} directory to avoid duplicates in the future."
rm ${CSVFILE}
rm csvfile.txt
rm confirmation.txt

else
#----------------------------------------------------
#if the directory is empty
#------------------------------------------------------
echo -e "Please make sure the CSV file was downloaded to ${Purple}$FILEDIR${ColorOFF} directory and run the script again."

fi


###
#--------THE END---------------------------------
###

这是脚本的一些输出。

  • IFS =,
  • 阅读v1 v2 v3 v4其他 ++ echo p098650 ++ tr'“/,\&amp;' ''
  • V2 = p098650
  • NAME =($ {V2})
  • CNT = 1
  • [[p098650 =〜[P | p] [[:digit:]] {6} $ | [J | j] [[:digit:]] {5} $]] ++ getent passwd p098650 ++ awk -F:'{print $ 1}'
  • ADresult1 = p098650
  • echo p098650 p098650
  • 声明-A arrmail
  • arrmail [$ ADresult1] ='CNU327B1Y3,EDGARLITE_0340_COR_00'
  • appendvar + ='; CNU327B1Y3,EDGARLITE_0340_COR_00'
  • '[''!' -z'CNU327B1Y3,EDGARLITE_0340_COR_00'']'
  • echo CNU327B1Y3,EDGARLITE_0340_COR_00 CNU327B1Y3,EDGARLITE_0340_COR_00
  • echo'NEXT ROW' 下一行
  • IFS =,
  • 阅读v1 v2 v3 v4其他 ++ echo p098650 ++ tr'“/,\&amp;' ''
  • V2 = p098650
  • NAME =($ {V2})
  • CNT = 1
  • [[p098650 =〜[P | p] [[:digit:]] {6} $ | [J | j] [[:digit:]] {5} $]] ++ getent passwd p098650 ++ awk -F:'{print $ 1}'
  • ADresult1 = p098650
  • echo p098650 p098650
  • 声明-A arrmail
  • arrmail [$ ADresult1] ='CNU327B1GP,BUZZLITE_0340_COR_00'
  • appendvar + ='; CNU327B1GP,BUZZLITE_0340_COR_00'
  • '[''!' -z'CNU327B1GP,BUZZLITE_0340_COR_00'']'
  • echo CNU327B1GP,BUZZLITE_0340_COR_00 CNU327B1GP,BUZZLITE_0340_COR_00
  • echo'NEXT ROW' 下一行

我期待看到的是,arrmail [$ ADresult1] ='CNU327B1Y3,EDGARLITE_0340_COR_00';'CNU327B1GP,BUZZLITE_0340_COR_00'

我无法包含CSV的屏幕截图,所以我只是剪切并粘贴其中一些。

Sernum $ V1用户名$ V2努力$ V3 Startdate $ V4

CNU327B1Y3 p098650 EDGARLITE_0340_COR_00 4-Mar-14

CNU3199N31 Bell SDLCONTENTPORTER_2013_COR_00 10-Mar-14

CNU327B1GP p098650 BUZZLITE_0340_COR_00 4-Mar-14

CNU2479GLB Mike XENDESKAGENTX64_0640_COR_00 28-Feb-14

CNU327B1PB Mike Bell BONDONEUOBRA_2001_COR_00 6-Mar-14

2UA24705YY Bell Mike SASENTGUIDEX64_0610_COR_00 25-Nov-13

CNU2479K7Z贝尔,迈克软件测试12-Dec-13

2UA24705ZZ Bell Mike TESTGUIDEX64_0610_COR_00 25-Nov-13

我知道这很多。我已经在这方面工作了很长时间,我正在努力更好地理解如何使用和操作数组。此外,如果您有关于该主题的书籍的建议,我也很乐意审查这些。提前感谢您的帮助。

0 个答案:

没有答案