Delete files with a specific pattern using script in UNIX
I have some folders in unix, lets say aa, ab, ac and so on. I have subfolders inside these folders. They are numbered like 100, 200 and so on. I want to delete some sub folders in each of these main folders. The sub folders to be deleted must be greater than a specific number(say anything above 开发者_StackOverflow社区700) How can I do this using a script? Please help.
I would use the find
command. You can do something like this:
find . -name '[7-9][0-9][0-9]' -execdir echo 'rm -vr' {} +
Of course, you may need to tweak the pattern to hit the right names, but I would need more information to help with that.
#!/bin/bash
if [ $# -ne 2 ]
then
echo Usage: $0 searchdir limit
exit 1
fi
searchdir="$1"
limit="$2"
find $searchdir -type d |
egrep "/[0-9]+$" |
while read dirname
do
let num=`basename "$dirname"`
if [ $num -ge $limit ]
then
echo rm -rf "$dirname"
fi
done
Run with: ./script.sh dirtosearch thresholdfordelete
When you're sure it's ok, remove the echo before rm -rf
You can do it all using find
.
In the following command, find
passes the files to sh
which checks if they are >700 and if so echoes out a delete. (You can obviously remove the echo
if you really want to delete.)
find . -type d -regex "^.*/[0-9]+$" -exec sh -c 'f="{}";[ $(basename "$f") -gt 700 ] && echo "rm -rf $f"' \;
精彩评论