We help IT Professionals succeed at work.
Get Started

Loop through files in Unix, grab substrings in each and email to appropriate users

XOracle asked
Last Modified: 2012-08-14

Forgive me for the ugly attempt that I have made, but as you can see, I am no Unix expert. I want to loop through all records in a particular directory /mydir/test and look for all files that are in the following format RPT_TEST_ENROLL_XXX_YYYYMMDD.TXT. I would then like to grab each file, grab the XXX value from each (which may be variable in length) and then send the file to an email address associated with the XXX. Hope that makes sense. Maybe you can tell what I was attempting to do by what I've thrown together.

Thank you very much for your time.

t_date=`date +%Y%m%d`

    ls -1  *${rpt_file}*${t_date}.TXT > ${txt_files}
    for txt_files in `cat ${txt_files}`
    # example file RPT_TEST_ENROLL_1024_20071113.TXT
    # is 33 characters long without the 1024,
    # which will change with every file
# get the length of the file, minus 33 which should give us the length of the uniqu ID
# now grab that ID using a substring
# now concatenate the unique ID in between DC and @myemail.com to form the email address
     email=DC $id_code @myemail.com
# Now ssend the email with the attachment to the appropriate address
      uuencode $txt_files $txt_files| mailx -s 'New Enrollments' $email

   if [ ${?} -ne 0 ]
      echo "An error occurred while emailing the file ${txt_files}"

 echo "Successfully emailed the file ${txt_files}."
Watch Question
Most Valuable Expert 2014
Top Expert 2015
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE