Greetings,
I'm doing a process whereby I need to search for all filenames containing a given bit of text and grab the newest file from what may be 20 results. In a script I'm writing,
i've got a monster line to do the sort as follows:
find /opt/work/reports/input -name "*$searchtarget*" | xargs ls -l --time-style="+%Y%m%d%H%M%S" | awk '{print $6 " " $7}' | sort -nr | head -n1 | awk '{print $2}'
This seems to be terribly inefficient and induce a lot of process forking. Is there an easier, simpler way to do this?
Can those files be located in subdirectories under /opt/work/reports/input? Or are they stored directly in that directory?
Yes, they can. There are one of two subfolders (besides the main folder) that a search result could possibly reside in.
Try if this works for you:
find /opt/work/reports/input -name "*$searchtarget*" -exec ls -l --time-style=+%s {} \; | sort -rnk6 | head -1
This should be pretty efficient:
find /opt/work/reports/input -name "*$searchtarget*" -exec ls -n --time-style=+%s {} + | awk '$6>m {m=$6;o=$7} END{print o}'