简体   繁体   中英

How to sort output of the find command in a script

I have the following simple script to find all directories (at a depth of 2) that were added in the last N days...

#!/bin/bash
DAYS_PRIOR=180
DIR='/mydir'
FILES=`find $DIR -mindepth 2 -maxdepth 2 -type d -mtime -$DAYS_PRIOR -printf '%f\\\n'`
echo
echo "Files added in the last $DAYS_PRIOR days:"
echo
echo -e $FILES
echo

To get it to add newlines I had to double-escape the printf and use echo -e . That seems odd to me but it was the only way I could get it to print one directory per line on the output.

Everything works up to this point and I get a list of directories as expected. Now I want to sort the list alphabetically. I tried changing the printf in the find command to...

FILES=`find <xxx> -printf '%f\\\n' | sort`

however this doesn't sort the directory names. Based on other posts I tried the following..

FILES=`find <xxx> -printf %f\\\n | sort -t '\0' | awk -F '\0' '{print $0; print "\\\n"}'`

This is very close but leaves an extra space at the start of each line and seems horribly awkward.

Is there a simple method to add a sort to the original find command?

First: double-quote your variable references! When you use echo -e $FILES , the variable FILE 's value gets split into "words" based on whitespace (spaces, tabs, and newlines), and then echo sticks those words back together with spaces between them. This has the effect of converting newlines into spaces. In order to wind up with newlines at the end, you're having to use \\n instead of a true newline, and use echo -e to convert it. Just use real newlines, and put double-quotes around the variable reference to avoid all this mess:

FILES=$(find "$DIR" -mindepth 2 -maxdepth 2 -type d -mtime "-$DAYS_PRIOR" -printf '%f\n')
# ...
echo "$FILES"

Note that I put double-quotes around all variable references, since this is almost always a good idea. I also used $( ) instead of backticks -- it's easier to read, and avoids some parsing oddities that backticks have.

Anyway, with this format you're using proper newlines throughout, so piping through sort should work as expected.

BTW, I'd also recommend switching from uppercase variable names to lower- or mixed-case names, since there are a bunch of all-caps names that have special meanings, and if you accidentally use one of them bad things can happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM