Maxtech
Maxtech

Reputation: 111

How to find the particular files in a directory in a shell script?

I'm trying to find the particular below files in the directory using find command pattern in shell script .

The below files will create in the directory "/data/output" in the below format every time.

 PO_ABCLOAD0626201807383269.txt
 PO_DEF 0626201811383639.txt

So I need to find the above txt files starting from "PO_ABCLOAD" and "PO_DEF" is created or not.if not create for four hours then I need to write in logs.

I written script but I am stuck up to find the file "PO_ABCLOAD" and "PO_DEF format text file in the below script.

Please help on this.

What changes i need to add in the find command.

My script is:

file_path=/data/output

PO_count='find ${file_path}/PO/*.txt  -mtime +4  -exec ls -ltr {} + | wc -l'

if [ $PO_count == 0 ]
then
   find ${file_path}/PO/*.xml -mtime +4 -exec ls -ltr {} + > 
 /logs/test/PO_list.txt

fi 

Thanks in advance

Upvotes: 2

Views: 950

Answers (1)

David Collins
David Collins

Reputation: 3012

Welcome to the forum. To search for files which match the names you are looking for you could try the -iname or -name predicates. However, there are other issues with your script.

Modification times

Firstly, I think that find's -mtime test works in a different way than you expect. From the manual:

-mtime n
File's data was last modified n*24 hours ago.

So if, for example, you run

find . -mtime +4

you are searching for files which are more than four days old. To search for files that are more than four hours old, I think you need to use the -mmin option instead; this will search for files which were modified a certain number of minutes ago.

Command substitution syntax

Secondly, using ' for command substitution in Bash will not work: you need to use backticks instead - as in

PO_COUNT=`find ...`

instead of

PO_COUNT='find ...'

Alternatively - even better (as codeforester pointed out in a comment) - use $(...) - as in

PO_COUNT=$(find ...)

Redundant options

Thirdly, using -exec ls -ltr {} + is redundant in this context - since all you are doing is determining the number of lines in the output.

So the relevant line in your script might become something like

PO_COUNT=$(find $FILE_PATH/PO/ -mmin +240 -a -name 'PO_*' | wc -l)

or

PO_COUNT=$(find $FILE_PATH/PO/PO_* -mmin +240 | wc -l)

If you wanted tighter matching of filenames, try (as per codeforester's suggestion) something like

PO_COUNT=$(find $file_path/PO/PO_* -mmin +240 -a \( -name 'PO_DEF*' -o -name 'PO_ABCLOAD*' \) | wc -l)

Alternative file-name matching in Bash

One last thing ... If using bash, you can use brace expansion to match filenames, as in

PO_COUNT=$(find $file_path/PO/PO_{ABCLOAD,DEF}* -mmin +240 | wc -l)

Although this is slightly more concise, I don't think it is compatible with all shells.

Upvotes: 2

Related Questions