Execute a command in different directory through Unix Script

Hi Gurus,

I have the below requirement,

Execute an unix script which will pick the latest file from the archive directory and do a grep (on multiple patterns) on that file.

processingDir="/usr/apps/irdc/informatica/spsf_sales/TgtFiles/ARCHIVE"
filename = 'ls Check* | sort -n -k 2 | tail -1'

The processing directory contains the list of archive files and the file name command will retrieve the latest timestamp file and the below command does the egrep.

egrep 'CHECKS NOT BALANCED|
PAYMENTS ARE OUT OF BALANCE' filename

Problem:

  1. I am not sure how to execute the fileName command in the processing directory and look for the egrep on the retrieved file.
  2. When executed the egrep on the file, the command expects the file to be set to have the execute privilges, how can i set that during run time.

Your thoughts and inputs please.

 
#!/bin/sh
 
processingDir="/usr/apps/irdc/informatica/spsf_sales/TgtFiles/ARCHIVE"
filename=`ls -1tr $processingDir/Check* | tail -1`
 
egrep 'CHECKS NOT BALANCED|PAYMENTS ARE OUT OF BALANCE' $filename
 

Hi,

Try this one,

#! /usr/bin/env bash

processingDir="/usr/apps/irdc/informatica/spsf_sales/TgtFiles/ARCHIVE"
filename="ls $processingDir/Check* | sort -n -k 2 | tail -1"

file=$(eval $filename)
echo "File Name:${file}"

Cheers,
Ranga :slight_smile:

how your filename looks like ?

post the sameple filenames. and is that having any timestamp ?

you can retrieve the last filename like

filename=$(ls -lrt Check* | awk '{a=$NF}END{print a}' )

if you want to check whether the file has read permission ( egrep needs ), you can check like...

[ -r ${filename} ] || chmod 444 ${filename}
egrep  'CHECKS NOT BALANCED|PAYMENTS ARE OUT OF BALANCE' ${filename}

make sure, the user has rights to change the file permission

---------- Post updated at 09:38 PM ---------- Previous update was at 09:38 PM ----------

ls -lrt | tail -1 ---> will not give the filename

Thank you itkamaraj.

Check_Report.txt.10182012.041335
Check_Report.txt.10172012.041315
Check_Report.txt.10162012.041325

Can you please let me know how could i execute the command in that folder and do an egrep.

#!/bin/sh
 
processingDir="/usr/apps/irdc/informatica/spsf_sales/TgtFiles/ARCHIVE"
filename=$(ls -lrt $processingDir | awk '{a=$NF}END{print a}')

echo "Filename : ${filename}"
echo "Checking if ${filename} has read permission for the user. If not assign read permission"

[ -r ${filename} ] && echo "File ${filename} has read permission" || chmod 444 ${filename}

#Now do egrep
egrep 'CHECKS NOT BALANCED|PAYMENTS ARE OUT OF BALANCE' ${filename}

if you want to grep the today's file (only one file per day), then

filename=$(ls Check_Report.txt.$(date +%m%d%Y)*)

Hi Kamaraj,

Again for egrep we need to provide the complete path with the file name right???

I guess providing only the file name will result in file not found error.